task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #SNOBOL4 | SNOBOL4 |
DEFINE("countSubstring(t,s)")
OUTPUT = countSubstring("the three truths","th")
OUTPUT = countSubstring("ababababab","abab")
:(END)
countSubstring t ARB s = :F(RETURN)
countSubstring = countSubstring + 1 :(countSubstring)
END
3
2
|
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequence is a similar task without the use of octal numbers.
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 PRINT "DEC. OCT."
20 FOR i=0 TO 20
30 LET o$="": LET n=i
40 LET o$=STR$ FN m(n,8)+o$
50 LET n=INT (n/8)
60 IF n>0 THEN GO TO 40
70 PRINT i;TAB 3;" = ";o$
80 NEXT i
90 STOP
100 DEF FN m(a,b)=a-INT (a/b)*b |
http://rosettacode.org/wiki/Count_in_factors | Count in factors | Task
Write a program which counts up from 1, displaying each number as the multiplication of its prime factors.
For the purpose of this task, 1 (unity) may be shown as itself.
Example
2 is prime, so it would be shown as itself.
6 is not prime; it would be shown as
2
×
3
{\displaystyle 2\times 3}
.
2144 is not prime; it would be shown as
2
×
2
×
2
×
2
×
2
×
67
{\displaystyle 2\times 2\times 2\times 2\times 2\times 67}
.
Related tasks
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
| #Visual_Basic_.NET | Visual Basic .NET | Module CountingInFactors
Sub Main()
For i As Integer = 1 To 10
Console.WriteLine("{0} = {1}", i, CountingInFactors(i))
Next
For i As Integer = 9991 To 10000
Console.WriteLine("{0} = {1}", i, CountingInFactors(i))
Next
End Sub
Private Function CountingInFactors(ByVal n As Integer) As String
If n = 1 Then Return "1"
Dim sb As New Text.StringBuilder()
CheckFactor(2, n, sb)
If n = 1 Then Return sb.ToString()
CheckFactor(3, n, sb)
If n = 1 Then Return sb.ToString()
For i As Integer = 5 To n Step 2
If i Mod 3 = 0 Then Continue For
CheckFactor(i, n, sb)
If n = 1 Then Exit For
Next
Return sb.ToString()
End Function
Private Sub CheckFactor(ByVal mult As Integer, ByRef n As Integer, ByRef sb As Text.StringBuilder)
Do While n Mod mult = 0
If sb.Length > 0 Then sb.Append(" x ")
sb.Append(mult)
n = n / mult
Loop
End Sub
End Module |
http://rosettacode.org/wiki/Create_an_HTML_table | Create an HTML table | Create an HTML table.
The table body should have at least three rows of three columns.
Each of these three columns should be labelled "X", "Y", and "Z".
An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less.
The numbers should be aligned in the same fashion for all columns.
| #PicoLisp | PicoLisp | (load "@lib/xhtml.l")
(<table> NIL NIL '(NIL (NIL "X") (NIL "Y") (NIL "Z"))
(for N 3
(<row> NIL N 124 456 789) ) ) |
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Toka | Toka | needs shell
" output.txt" "W" file.open file.close
" /output.txt" "W" file.open file.close
( Create the directories with permissions set to 777)
" docs" &777 mkdir
" /docs" &777 mkdir |
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
- create file
ERROR/STOP CREATE ("output.txt",FDF-o,-std-)
- create directory
ERROR/STOP CREATE ("docs",project,-std-)
|
http://rosettacode.org/wiki/CSV_to_HTML_translation | CSV to HTML translation | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
Create a function that takes a string representation of the CSV data
and returns a text string of an HTML table representing the CSV data.
Use the following data as the CSV text to convert, and show your output.
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
Extra credit
Optionally allow special formatting for the first row of the table as if it is the tables header row
(via <thead> preferably; CSS if you must).
| #Rust | Rust | static INPUT : &'static str =
"Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!";
fn main() {
print!("<table>\n<tr><td>");
for c in INPUT.chars() {
match c {
'\n' => print!("</td></tr>\n<tr><td>"),
',' => print!("</td><td>"),
'<' => print!("<"),
'>' => print!(">"),
'&' => print!("&"),
_ => print!("{}", c)
}
}
println!("</td></tr>\n</table>");
}
|
http://rosettacode.org/wiki/Cumulative_standard_deviation | Cumulative standard deviation | Task[edit]
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.
The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task must state which is being used.
Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.
Test case
Use this to compute the standard deviation of this demonstration set,
{
2
,
4
,
4
,
4
,
5
,
5
,
7
,
9
}
{\displaystyle \{2,4,4,4,5,5,7,9\}}
, which is
2
{\displaystyle 2}
.
Related tasks
Random numbers
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #TI-83_BASIC | TI-83 BASIC | • Press [STAT] select [EDIT] followed by [ENTER]
• then enter for list L1 in the table : 2, 4, 4, 4, 5, 5, 7, 9
• Or enter {2,4,4,4,5,5,7,9}→L1
• Press [STAT] select [CALC] then [1-Var Stats] select list L1 followed by [ENTER]
• Then σx (=2) gives the standard deviation of the population
|
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Standard_ML | Standard ML | fun count_substrings (str, sub) =
let
fun aux (str', count) =
let
val suff = #2 (Substring.position sub str')
in
if Substring.isEmpty suff then
count
else
aux (Substring.triml (size sub) suff, count + 1)
end
in
aux (Substring.full str, 0)
end;
print (Int.toString (count_substrings ("the three truths", "th")) ^ "\n");
print (Int.toString (count_substrings ("ababababab", "abab")) ^ "\n");
print (Int.toString (count_substrings ("abaabba*bbaba*bbab", "a*b")) ^ "\n"); |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Stata | Stata | function strcount(s, x) {
n = 0
k = 1-(i=strlen(x))
do {
if (k = ustrpos(s, x, k+i)) n++
} while(k)
return(n)
}
strcount("peter piper picked a peck of pickled peppers", "pe")
5
strcount("ababababab","abab")
2 |
http://rosettacode.org/wiki/Count_in_factors | Count in factors | Task
Write a program which counts up from 1, displaying each number as the multiplication of its prime factors.
For the purpose of this task, 1 (unity) may be shown as itself.
Example
2 is prime, so it would be shown as itself.
6 is not prime; it would be shown as
2
×
3
{\displaystyle 2\times 3}
.
2144 is not prime; it would be shown as
2
×
2
×
2
×
2
×
2
×
67
{\displaystyle 2\times 2\times 2\times 2\times 2\times 67}
.
Related tasks
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
| #Vlang | Vlang | fn main() {
println("1: 1")
for i := 2; ; i++ {
print("$i: ")
mut x := ''
for n, f := i, 2; n != 1; f++ {
for m := n % f; m == 0; m = n % f {
print('$x$f')
x = "×"
n /= f
}
}
println('')
}
} |
http://rosettacode.org/wiki/Count_in_factors | Count in factors | Task
Write a program which counts up from 1, displaying each number as the multiplication of its prime factors.
For the purpose of this task, 1 (unity) may be shown as itself.
Example
2 is prime, so it would be shown as itself.
6 is not prime; it would be shown as
2
×
3
{\displaystyle 2\times 3}
.
2144 is not prime; it would be shown as
2
×
2
×
2
×
2
×
2
×
67
{\displaystyle 2\times 2\times 2\times 2\times 2\times 67}
.
Related tasks
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
| #XPL0 | XPL0 | include c:\cxpl\codes;
int N0, N, F;
[N0:= 1;
repeat IntOut(0, N0); Text(0, " = ");
F:= 2; N:= N0;
repeat if rem(N/F) = 0 then
[if N # N0 then Text(0, " * ");
IntOut(0, F);
N:= N/F;
]
else F:= F+1;
until F>N;
if N0=1 then IntOut(0, 1); \1 = 1
CrLf(0);
N0:= N0+1;
until KeyHit;
] |
http://rosettacode.org/wiki/Create_an_HTML_table | Create an HTML table | Create an HTML table.
The table body should have at least three rows of three columns.
Each of these three columns should be labelled "X", "Y", and "Z".
An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less.
The numbers should be aligned in the same fashion for all columns.
| #PL.2FI | PL/I |
/* Create an HTML table. 6/2011 */
create: procedure options (main);
create_table: procedure (headings, table_contents);
declare headings(*) character (10) varying;
declare table_contents(*, *) fixed;
declare (i, row, col) fixed;
put skip edit ('<table>') (a);
/* Headings. */
put skip edit ('<tr><th></th> ') (a);
/* For an empty column heading */
do i = 1 to hbound(headings);
put edit ('<th>', headings(i), '</th> ' ) (a);
end;
put edit ('</tr>') (a);
/* Table contents. */
do row = 1 to hbound(table_contents, 1);
/* row number */
put skip edit ('<tr><td>', row, '</td> ') (a);
/* row contents */
do col = 1 to hbound(table_contents, 2);
put edit ('<td>', table_contents(row, col), '</td> ' ) (a);
end;
put edit ('</tr>') (a);
end;
put skip edit ('</table>' ) (a);
end create_table;
declare headings (3) character (1) static initial ('X', 'Y', 'Z');
declare table_contents(3, 3) fixed static initial (
4, -3, 8,
7, 2, -6,
11, 1, 15);
call create_table (headings, table_contents);
end create; |
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #UNIX_Shell | UNIX Shell | touch output.txt /output.txt # create both output.txt and /output.txt
mkdir /docs
mkdir docs # create both /docs and docs |
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Ursa | Ursa | decl file f
f.create "output.txt"
f.createdir "docs"
# in the root directory
f.create "/output.txt"
f.createdir "/docs"
|
http://rosettacode.org/wiki/CSV_to_HTML_translation | CSV to HTML translation | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
Create a function that takes a string representation of the CSV data
and returns a text string of an HTML table representing the CSV data.
Use the following data as the CSV text to convert, and show your output.
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
Extra credit
Optionally allow special formatting for the first row of the table as if it is the tables header row
(via <thead> preferably; CSS if you must).
| #Scala | Scala | object CsvToHTML extends App {
val header = <head>
<title>CsvToHTML</title>
<style type="text/css">
td {{background-color:#ddddff; }} thead td {{background-color:#ddffdd; text-align:center; }}
</style>
</head>
val csv =
"""Character,Speech
|The multitude,The messiah! Show us the messiah!
|Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
|The multitude,Who are you?
|Brians mother,I'm his mother; that's who!
|The multitude,Behold his mother! Behold his mother!""".stripMargin
def csv2html(csv: String, withHead: Boolean) = {
def processRow(text: String) = <tr>
{text.split(',').map(s => <td>
{s}
</td>)}
</tr>
val (first :: rest) = csv.lines.toList // Separate the header and the rest
def tableHead = if (withHead)
<thead>
{processRow(first)}
</thead>
else processRow(first)
<html>
{header}<body>
<table>
{tableHead}{rest.map(processRow)}
</table>
</body>
</html>
}
println(csv2html(csv, true))
} |
http://rosettacode.org/wiki/Cumulative_standard_deviation | Cumulative standard deviation | Task[edit]
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.
The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task must state which is being used.
Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.
Test case
Use this to compute the standard deviation of this demonstration set,
{
2
,
4
,
4
,
4
,
5
,
5
,
7
,
9
}
{\displaystyle \{2,4,4,4,5,5,7,9\}}
, which is
2
{\displaystyle 2}
.
Related tasks
Random numbers
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #VBScript | VBScript | data = Array(2,4,4,4,5,5,7,9)
For i = 0 To UBound(data)
WScript.StdOut.Write "value = " & data(i) &_
" running sd = " & sd(data,i)
WScript.StdOut.WriteLine
Next
Function sd(arr,n)
mean = 0
variance = 0
For j = 0 To n
mean = mean + arr(j)
Next
mean = mean/(n+1)
For k = 0 To n
variance = variance + ((arr(k)-mean)^2)
Next
variance = variance/(n+1)
sd = FormatNumber(Sqr(variance),6)
End Function |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Swift | Swift | import Foundation
func countSubstring(str: String, substring: String) -> Int {
return str.components(separatedBy: substring).count - 1
}
print(countSubstring(str: "the three truths", substring: "th"))
print(countSubstring(str: "ababababab", substring: "abab")) |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Tcl | Tcl | proc countSubstrings {haystack needle} {
regexp -all ***=$needle $haystack
}
puts [countSubstrings "the three truths" "th"]
puts [countSubstrings "ababababab" "abab"]
puts [countSubstrings "abaabba*bbaba*bbab" "a*b"] |
http://rosettacode.org/wiki/Count_in_factors | Count in factors | Task
Write a program which counts up from 1, displaying each number as the multiplication of its prime factors.
For the purpose of this task, 1 (unity) may be shown as itself.
Example
2 is prime, so it would be shown as itself.
6 is not prime; it would be shown as
2
×
3
{\displaystyle 2\times 3}
.
2144 is not prime; it would be shown as
2
×
2
×
2
×
2
×
2
×
67
{\displaystyle 2\times 2\times 2\times 2\times 2\times 67}
.
Related tasks
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
| #Wren | Wren | import "/math" for Int
for (r in [1..9, 2144..2154, 9987..9999]) {
for (i in r) {
var factors = (i > 1) ? Int.primeFactors(i) : [1]
System.print("%(i): %(factors.join(" x "))")
}
System.print()
} |
http://rosettacode.org/wiki/Count_in_factors | Count in factors | Task
Write a program which counts up from 1, displaying each number as the multiplication of its prime factors.
For the purpose of this task, 1 (unity) may be shown as itself.
Example
2 is prime, so it would be shown as itself.
6 is not prime; it would be shown as
2
×
3
{\displaystyle 2\times 3}
.
2144 is not prime; it would be shown as
2
×
2
×
2
×
2
×
2
×
67
{\displaystyle 2\times 2\times 2\times 2\times 2\times 67}
.
Related tasks
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
| #zkl | zkl | foreach n in ([1..*]){ println(n,": ",primeFactors(n).concat("\U2715;")) } |
http://rosettacode.org/wiki/Create_an_HTML_table | Create an HTML table | Create an HTML table.
The table body should have at least three rows of three columns.
Each of these three columns should be labelled "X", "Y", and "Z".
An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less.
The numbers should be aligned in the same fashion for all columns.
| #PowerShell | PowerShell |
# Converts Microsoft .NET Framework objects into HTML that can be displayed in a Web browser.
ConvertTo-Html -inputobject (Get-Date)
# Create a PowerShell object using a HashTable
$object = [PSCustomObject]@{
'A'=(Get-Random -Minimum 0 -Maximum 10);
'B'=(Get-Random -Minimum 0 -Maximum 10);
'C'=(Get-Random -Minimum 0 -Maximum 10)}
$object | ConvertTo-Html
|
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #VBA | VBA | Public Sub create_file()
Dim FileNumber As Integer
FileNumber = FreeFile
MkDir "docs"
Open "docs\output.txt" For Output As #FreeFile
Close #FreeFile
MkDir "C:\docs"
Open "C:\docs\output.txt" For Output As #FreeFile
Close #FreeFile
End Sub |
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #VBScript | VBScript |
Set objFSO = CreateObject("Scripting.FileSystemObject")
'current directory
objFSO.CreateFolder(".\docs")
objFSO.CreateTextFile(".\docs\output.txt")
'root directory
objFSO.CreateFolder("\docs")
objFSO.CreateTextFile("\docs\output.txt")
|
http://rosettacode.org/wiki/CSV_to_HTML_translation | CSV to HTML translation | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
Create a function that takes a string representation of the CSV data
and returns a text string of an HTML table representing the CSV data.
Use the following data as the CSV text to convert, and show your output.
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
Extra credit
Optionally allow special formatting for the first row of the table as if it is the tables header row
(via <thead> preferably; CSS if you must).
| #Sed | Sed | #!/bin/sed -f
s|<|\<|g
s|>|\>|g
s|^| <tr>\n <td>|
s|,|</td>\n <td>|
s|$|</td>\n </tr>|
1s|^|<table>\n|
$s|$|\n</table>| |
http://rosettacode.org/wiki/Cumulative_standard_deviation | Cumulative standard deviation | Task[edit]
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.
The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task must state which is being used.
Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.
Test case
Use this to compute the standard deviation of this demonstration set,
{
2
,
4
,
4
,
4
,
5
,
5
,
7
,
9
}
{\displaystyle \{2,4,4,4,5,5,7,9\}}
, which is
2
{\displaystyle 2}
.
Related tasks
Random numbers
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Visual_Basic | Visual Basic | Function avg(what() As Variant) As Variant
'treats non-numeric strings as zero
Dim L0 As Variant, total As Variant
For L0 = LBound(what) To UBound(what)
If IsNumeric(what(L0)) Then total = total + what(L0)
Next
avg = total / (1 + UBound(what) - LBound(what))
End Function
Function standardDeviation(fp As Variant) As Variant
Static list() As Variant
Dim av As Variant, tmp As Variant, L0 As Variant
'add to sequence if numeric
If IsNumeric(fp) Then
On Error GoTo makeArr 'catch undimensioned list
ReDim Preserve list(UBound(list) + 1)
On Error GoTo 0
list(UBound(list)) = fp
End If
'get average
av = avg(list())
'the actual work
For L0 = 0 To UBound(list)
tmp = tmp + ((list(L0) - av) ^ 2)
Next
tmp = Sqr(tmp / (UBound(list) + 1))
standardDeviation = tmp
Exit Function
makeArr:
If 9 = Err.Number Then
ReDim list(0)
Else
'something's wrong
Err.Raise Err.Number
End If
Resume Next
End Function
Sub tester()
Dim x As Variant
x = Array(2, 4, 4, 4, 5, 5, 7, 9)
For L0 = 0 To UBound(x)
Debug.Print standardDeviation(x(L0))
Next
End Sub |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Transd | Transd | #lang transd
MainModule: {
countSubstring: (λ s String() sub String()
(with n 0 pl 0
(while (> (= pl (find s sub pl)) -1)
(+= pl (size sub)) (+= n 1))
(lout n))
),
_start: (λ
(countSubstring "the three truths" "th")
(countSubstring "ababababab" "abab")
)
} |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT, {}
occurences=COUNT ("the three truths", ":th:")
occurences=COUNT ("ababababab", ":abab:")
occurences=COUNT ("abaabba*bbaba*bbab",":a\*b:")
|
http://rosettacode.org/wiki/Count_in_factors | Count in factors | Task
Write a program which counts up from 1, displaying each number as the multiplication of its prime factors.
For the purpose of this task, 1 (unity) may be shown as itself.
Example
2 is prime, so it would be shown as itself.
6 is not prime; it would be shown as
2
×
3
{\displaystyle 2\times 3}
.
2144 is not prime; it would be shown as
2
×
2
×
2
×
2
×
2
×
67
{\displaystyle 2\times 2\times 2\times 2\times 2\times 67}
.
Related tasks
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 FOR i=1 TO 20
20 PRINT i;" = ";
30 IF i=1 THEN PRINT 1: GO TO 90
40 LET p=2: LET n=i: LET f$=""
50 IF p>n THEN GO TO 80
60 IF NOT FN m(n,p) THEN LET f$=f$+STR$ p+" x ": LET n=INT (n/p): GO TO 50
70 LET p=p+1: GO TO 50
80 PRINT f$( TO LEN f$-3)
90 NEXT i
100 STOP
110 DEF FN m(a,b)=a-INT (a/b)*b |
http://rosettacode.org/wiki/Create_an_HTML_table | Create an HTML table | Create an HTML table.
The table body should have at least three rows of three columns.
Each of these three columns should be labelled "X", "Y", and "Z".
An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less.
The numbers should be aligned in the same fashion for all columns.
| #Prolog | Prolog |
:- use_module(library(http/html_write)).
theader([]) --> []. theader([H|T]) --> html(th(H)), theader(T).
trows([],_) --> []. trows([R|T], N) --> html(tr([td(N),\trow(R)])), { N1 is N + 1 }, trows(T, N1).
trow([]) --> []. trow([E|T]) --> html(td(E)), trow(T).
table :-
Header = ['X','Y','Z'],
Rows = [
[7055,5334,5795],
[2895,3019,7747],
[140,7607,8144],
[7090,475,4140]
],
phrase(html(table([tr(\theader(Header)), \trows(Rows,1)])), Out, []),
print_html(Out). |
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Vedit_macro_language | Vedit macro language | // In current directory
File_Open("input.txt") Ins_Char(' ') Del_Char(-1) Buf_Close()
File_Mkdir("docs")
// In the root directory
File_Open("/input.txt") Ins_Char(' ') Del_Char(-1) Buf_Close()
File_Mkdir("/docs") |
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Visual_Basic_.NET | Visual Basic .NET | 'Current Directory
IO.Directory.CreateDirectory("docs")
IO.File.Create("output.txt").Close()
'Root
IO.Directory.CreateDirectory("\docs")
IO.File.Create("\output.txt").Close()
'Root, platform independent
IO.Directory.CreateDirectory(IO.Path.DirectorySeparatorChar & "docs")
IO.File.Create(IO.Path.DirectorySeparatorChar & "output.txt").Close() |
http://rosettacode.org/wiki/CSV_to_HTML_translation | CSV to HTML translation | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
Create a function that takes a string representation of the CSV data
and returns a text string of an HTML table representing the CSV data.
Use the following data as the CSV text to convert, and show your output.
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
Extra credit
Optionally allow special formatting for the first row of the table as if it is the tables header row
(via <thead> preferably; CSS if you must).
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "html_ent.s7i";
const string: csvData is "\
\Character,Speech\n\
\The multitude,The messiah! Show us the messiah!\n\
\Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\n\
\The multitude,Who are you?\n\
\Brians mother,I'm his mother; that's who!\n\
\The multitude,Behold his mother! Behold his mother!\n";
const proc: main is func
local
var string: line is "";
var string: column is "";
const array [boolean] string: columnStartTag is [boolean] ("<td>", "<th>");
const array [boolean] string: columnEndTag is [boolean] ("</td>", "</th>");
var boolean: firstLine is TRUE;
begin
writeln("<table>");
for line range split(csvData, '\n') do
write("<tr>");
for column range split(line, ',') do
write(columnStartTag[firstLine] <& encodeHtmlContent(column) <& columnEndTag[firstLine]);
end for;
writeln("</tr>");
firstLine := FALSE;
end for;
writeln("</table>");
end func; |
http://rosettacode.org/wiki/Cumulative_standard_deviation | Cumulative standard deviation | Task[edit]
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.
The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task must state which is being used.
Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.
Test case
Use this to compute the standard deviation of this demonstration set,
{
2
,
4
,
4
,
4
,
5
,
5
,
7
,
9
}
{\displaystyle \{2,4,4,4,5,5,7,9\}}
, which is
2
{\displaystyle 2}
.
Related tasks
Random numbers
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Wren | Wren | import "/fmt" for Fmt
import "/math" for Nums
var cumStdDev = Fiber.new { |a|
for (i in 0...a.count) {
var b = a[0..i]
System.print("Values : %(b)")
Fiber.yield(Nums.popStdDev(b))
}
}
var a = [2, 4, 4, 4, 5, 5, 7, 9]
while (true) {
var sd = cumStdDev.call(a)
if (cumStdDev.isDone) return
System.print("Std Dev : %(Fmt.f(10, sd, 8))\n")
} |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #TXR | TXR | @(next :args)
@(do (defun count-occurrences (haystack needle)
(for* ((occurrences 0)
(old-pos 0)
(new-pos (search-str haystack needle old-pos nil)))
(new-pos occurrences)
((inc occurrences)
(set old-pos (+ new-pos (length needle)))
(set new-pos (search-str haystack needle old-pos nil))))))
@ndl
@hay
@(output)
@(count-occurrences hay ndl) occurrences(s) of @ndl inside @hay
@(end) |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #UNIX_Shell | UNIX Shell | #!/bin/bash
function countString(){
input=$1
cnt=0
until [ "${input/$2/}" == "$input" ]; do
input=${input/$2/}
let cnt+=1
done
echo $cnt
}
countString "the three truths" "th"
countString "ababababab" "abab" |
http://rosettacode.org/wiki/Create_an_HTML_table | Create an HTML table | Create an HTML table.
The table body should have at least three rows of three columns.
Each of these three columns should be labelled "X", "Y", and "Z".
An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less.
The numbers should be aligned in the same fashion for all columns.
| #PureBasic | PureBasic |
Title.s="Create an HTML table"
head.s=""
head.s+"<html><head><title>"+Title.s+"</title></head><body>"+chr(13)+chr(10)
tablehead.s
tablehead.s+"<table border=1 cellpadding=10 cellspacing=0>"+chr(13)+chr(10)
tablehead.s+"<tr><th></th><th>X</th><th>Y</th><th>Z</th></tr>"+chr(13)+chr(10)
index=0
tablebody.s=""
for row=1 to 4
index+1
tablebody.s+"<tr><th>"+str(index)+"</th>"
for col=1 to 3
tablebody.s+"<td align="+chr(34)+"right"+chr(34)+">"+str(Random(9999,1))+"</td>"
next
tablebody.s+"</tr>"+chr(13)+chr(10)
next
tablefoot.s=""
tablefoot.s+"</table>"+chr(13)+chr(10)
foot.s=""
foot.s+"</body></html>"+chr(13)+chr(10)
FileName.s="Create_an_HTML_table.html"
If CreateFile(0,FileName.s)
WriteString(0,head.s)
WriteString(0,tablehead.s)
WriteString(0,tablebody.s)
WriteString(0,tablefoot.s)
WriteString(0,foot.s)
CloseFile(0)
Else
Debug "Not WriteString :"+FileName.s
EndIf
; RunProgram(FileName.s)
|
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Visual_Objects | Visual Objects |
DirMake(String2Psz("c:\docs"))
FCreate("c:\docs\output.txt", FC_NORMAL)
|
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Wren | Wren | import "io" for File
// file is closed automatically after creation
File.create("output.txt") {}
// check size
System.print("%(File.size("output.txt")) bytes") |
http://rosettacode.org/wiki/CSV_to_HTML_translation | CSV to HTML translation | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
Create a function that takes a string representation of the CSV data
and returns a text string of an HTML table representing the CSV data.
Use the following data as the CSV text to convert, and show your output.
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
Extra credit
Optionally allow special formatting for the first row of the table as if it is the tables header row
(via <thead> preferably; CSS if you must).
| #Sidef | Sidef | func escape(str) { str.trans(« & < > », « & < > ») }
func tag(t, d) { "<#{t}>#{d}</#{t}>" }
func csv2html(str) {
var template = <<-'EOT'
<!DOCTYPE html>
<html>
<head><title>Some Text</title></head>
<body><table>
%s
</table></body></html>
EOT
template.sprintf(escape(str).lines.map{ |line|
tag('tr', line.split(',').map{|cell| tag('td', cell) }.join)
}.join("\n")
)
}
var str = <<'EOT';
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
EOT
print csv2html(str) |
http://rosettacode.org/wiki/Cumulative_standard_deviation | Cumulative standard deviation | Task[edit]
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.
The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task must state which is being used.
Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.
Test case
Use this to compute the standard deviation of this demonstration set,
{
2
,
4
,
4
,
4
,
5
,
5
,
7
,
9
}
{\displaystyle \{2,4,4,4,5,5,7,9\}}
, which is
2
{\displaystyle 2}
.
Related tasks
Random numbers
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
int A, I;
real N, S, S2;
[A:= [2,4,4,4,5,5,7,9];
N:= 0.0; S:= 0.0; S2:= 0.0;
for I:= 0 to 8-1 do
[N:= N + 1.0;
S:= S + float(A(I));
S2:= S2 + float(sq(A(I)));
RlOut(0, sqrt((S2/N) - sq(S/N)));
];
CrLf(0);
] |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #VBA | VBA | Function CountStringInString(stLookIn As String, stLookFor As String)
CountStringInString = UBound(Split(stLookIn, stLookFor))
End Function |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #VBScript | VBScript |
Function CountSubstring(str,substr)
CountSubstring = 0
For i = 1 To Len(str)
If Len(str) >= Len(substr) Then
If InStr(i,str,substr) Then
CountSubstring = CountSubstring + 1
i = InStr(i,str,substr) + Len(substr) - 1
End If
Else
Exit For
End If
Next
End Function
WScript.StdOut.Write CountSubstring("the three truths","th") & vbCrLf
WScript.StdOut.Write CountSubstring("ababababab","abab") & vbCrLf
|
http://rosettacode.org/wiki/Create_an_HTML_table | Create an HTML table | Create an HTML table.
The table body should have at least three rows of three columns.
Each of these three columns should be labelled "X", "Y", and "Z".
An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less.
The numbers should be aligned in the same fashion for all columns.
| #Python | Python |
import random
def rand9999():
return random.randint(1000, 9999)
def tag(attr='', **kwargs):
for tag, txt in kwargs.items():
return '<{tag}{attr}>{txt}</{tag}>'.format(**locals())
if __name__ == '__main__':
header = tag(tr=''.join(tag(th=txt) for txt in ',X,Y,Z'.split(','))) + '\n'
rows = '\n'.join(tag(tr=tag(' style="font-weight: bold;"', td=i)
+ ''.join(tag(td=rand9999())
for j in range(3)))
for i in range(1, 6))
table = tag(table='\n' + header + rows + '\n')
print(table) |
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #X86_Assembly | X86 Assembly |
; syscall numbers for readability. :]
%define sys_mkdir 39
%define sys_creat 8
section .data
fName db 'doc/output.txt',0
rfName db '/output.txt',0
dName db 'doc',0
err_msg db "Something went wrong! :[",0xa
err_len equ $-err_msg
section .text
global _start
_start:
nop
mov ebx, dName ; Directory name
mov eax, sys_mkdir ; Specify sys_mkdir call
mov ecx, 0750o ; permission (rwxr-x---)
int 0x80 ; Make kernel call
mov ebx, fName ; File name
mov eax, sys_creat ; Specify sys_creat call
mov ecx, 0640o ; permission (rw-r-----)
int 0x80 ; Make kernel call
test eax, eax ; eax AND eax
js _ragequit ; If EAX is less than zero
; THEN Display Message Error
mov ebx, rfName ; File name Root
mov eax, sys_creat ; Specify sys_creat call
mov ecx, 0777o ; permission (rwxrwxrwx)
int 0x80 ; Make kernel call
cmp eax, 0
jle _exit ; IF EAX is less or equal than zero
; THEN jump to EXIT
; ELSE Display Message Error
_ragequit:
mov edx, err_len ; Pass offset of the message error
mov ecx, err_msg ; Pass the length of the message error
mov eax, 4 ; Specify sys_write call
mov ebx, 2 ; Specify File Descriptor 2: Error Output
int 0x80 ; Make kernel call
_exit:
push 0x1
mov eax, 1 ; Code for Exit Syscall
push eax
int 0x80 ; Make kernel call
ret
|
http://rosettacode.org/wiki/CSV_to_HTML_translation | CSV to HTML translation | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
Create a function that takes a string representation of the CSV data
and returns a text string of an HTML table representing the CSV data.
Use the following data as the CSV text to convert, and show your output.
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
Extra credit
Optionally allow special formatting for the first row of the table as if it is the tables header row
(via <thead> preferably; CSS if you must).
| #Tcl | Tcl | package require Tcl 8.5
package require csv
package require html
package require struct::queue
set csvData "Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!"
struct::queue rows
foreach line [split $csvData "\n"] {
csv::split2queue rows $line
}
html::init
puts [subst {
[html::openTag table {summary="csv2html program output"}]
[html::while {[rows size]} {
[html::row {*}[html::quoteFormValue [rows get]]]
}]
[html::closeTag]
}] |
http://rosettacode.org/wiki/Cumulative_standard_deviation | Cumulative standard deviation | Task[edit]
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.
The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task must state which is being used.
Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.
Test case
Use this to compute the standard deviation of this demonstration set,
{
2
,
4
,
4
,
4
,
5
,
5
,
7
,
9
}
{\displaystyle \{2,4,4,4,5,5,7,9\}}
, which is
2
{\displaystyle 2}
.
Related tasks
Random numbers
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #zkl | zkl | fcn sdf{ fcn(x,xs){
m:=xs.append(x.toFloat()).sum(0.0)/xs.len();
(xs.reduce('wrap(p,x){(x-m)*(x-m) +p},0.0)/xs.len()).sqrt()
}.fp1(L())
} |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Visual_Basic_.NET | Visual Basic .NET | Module Count_Occurrences_of_a_Substring
Sub Main()
Console.WriteLine(CountSubstring("the three truths", "th"))
Console.WriteLine(CountSubstring("ababababab", "abab"))
Console.WriteLine(CountSubstring("abaabba*bbaba*bbab", "a*b"))
Console.WriteLine(CountSubstring("abc", ""))
End Sub
Function CountSubstring(str As String, substr As String) As Integer
Dim count As Integer = 0
If (Len(str) > 0) And (Len(substr) > 0) Then
Dim p As Integer = InStr(str, substr)
Do While p <> 0
p = InStr(p + Len(substr), str, substr)
count += 1
Loop
End If
Return count
End Function
End Module |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Vlang | Vlang | fn main(){
println('the three truths'.count('th'))
println('ababababab'.count('abab'))
} |
http://rosettacode.org/wiki/Create_an_HTML_table | Create an HTML table | Create an HTML table.
The table body should have at least three rows of three columns.
Each of these three columns should be labelled "X", "Y", and "Z".
An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less.
The numbers should be aligned in the same fashion for all columns.
| #Racket | Racket |
#lang racket
(require xml)
(define xexpr
`(html
(head)
(body
(table
(tr (td) (td "X") (td "Y") (td "Z"))
,@(for/list ([i (in-range 1 4)])
`(tr (td ,(~a i))
(td ,(~a (random 10000)))
(td ,(~a (random 10000)))
(td ,(~a (random 10000)))))))))
(display-xml/content (xexpr->xml xexpr))
|
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #XPL0 | XPL0 |
int FD;
FD:= FOpen("output.txt", 1);
|
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Yabasic | Yabasic | open "output.txt" for writing as #1
close #1
system("mkdir " + "f:\docs")
if open(2, "f:\docs\output.txt") then
print "Subdirectory or file already exists"
else
open "f:\docs\output.txt" for writing as #2
close #2
end if |
http://rosettacode.org/wiki/CSV_to_HTML_translation | CSV to HTML translation | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
Create a function that takes a string representation of the CSV data
and returns a text string of an HTML table representing the CSV data.
Use the following data as the CSV text to convert, and show your output.
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
Extra credit
Optionally allow special formatting for the first row of the table as if it is the tables header row
(via <thead> preferably; CSS if you must).
| #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
MODE DATA
$$ csv=*
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
$$ htmlhead=*
<!DOCTYPE html system>
<html>
<head>
<title>Life of Brian</title>
<style type="text/css">
th {background-color:orange}
td {background-color:yellow}
</style></head><body><table>
$$ BUILD X_TABLE txt2html=*
<< <
>> >
$$ MODE TUSCRIPT
file="brian.html"
ERROR/STOP CREATE (file,FDF-o,-std-)
csv=EXCHANGE (csv,txt2html)
x=SPLIT (csv,":,:",row1,row2)
ACCESS html: WRITE/ERASE/RECORDS/UTF8 $file s,html
WRITE html htmlhead
LOOP n,td1=row1,td2=row2
IF (n==1) THEN
row=CONCAT ("<tr><th>",td1,"</th><th>",td2,"</th></tr>")
ELSE
row=CONCAT ("<tr><td>",td1,"</td><td>",td2,"</td></tr>")
ENDIF
WRITE html row
ENDLOOP
WRITE html "</table></body></html>"
ENDACCESS/PRINT html
|
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Wortel | Wortel | @let {
c &[s t] #!s.match &(t)g
[[
!!c "the three truths" "th"
!!c "ababababab" "abab"
]]
} |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Wren | Wren | import "/pattern" for Pattern
import "/fmt" for Fmt
var countSubstring = Fn.new { |str, sub|
var p = Pattern.new(sub)
return p.findAll(str).count
}
var tests = [
["the three truths", "th"],
["ababababab", "abab"],
["abaabba*bbaba*bbab", "a*b"],
["aaaaaaaaaaaaaa", "aa"],
["aaaaaaaaaaaaaa", "b"],
]
for (test in tests) {
var count = countSubstring.call(test[0], test[1])
Fmt.print("$6s occurs $d times in $q.", Fmt.q(test[1]), count, test[0])
} |
http://rosettacode.org/wiki/Create_an_HTML_table | Create an HTML table | Create an HTML table.
The table body should have at least three rows of three columns.
Each of these three columns should be labelled "X", "Y", and "Z".
An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less.
The numbers should be aligned in the same fashion for all columns.
| #Raku | Raku | my @header = < X Y Z>;
my $rows = 5;
sub tag ($tag, $string, $param?) { return "<$tag" ~ ($param ?? " $param" !! '') ~ ">$string" ~ "</$tag>" };
my $table = tag('tr', ( tag('th', $_) for @header));
for 1 .. $rows -> $row {
$table ~= tag('tr', ( tag('td', $row, 'align="right"')
~ (tag('td', (^10000).pick, 'align="right"') for 1..^@header)));
}
say tag('table', $table, 'cellspacing=4 style="text-align:right; border: 1px solid;"'); |
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #zkl | zkl | $ ls -l docs
ls: cannot access docs: No such file or directory
$ zkl
zkl: fcn createOutputTxt(dir){ dir=dir+"/docs"; File.mkdir(dir); File(dir+"/output.txt","w") }
Void
zkl: createOutputTxt(".")
File(./docs/output.txt)
zkl: createOutputTxt("/")
Stack trace for VM#1 ():
Cmd.createOutputTxt@mkdir addr:16 args(1) reg(0)
Cmd.__constructor@createOutputTxt addr:9 args(0) reg(0) R
startup.__constructor addr:2271 args(0) reg(1) ER
startup.__constructor addr:2207 args(0) reg(22)
Exception thrown: IOError(File.mkdir(//docs): Permission denied)
zkl: ^D
$ ls -l docs
total 0
-rw-r--r-- 1 craigd craigd 0 Oct 27 22:08 output.txt
|
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #ZX_Spectrum_Basic | ZX Spectrum Basic | SAVE "OUTPUT" CODE 16384,0 |
http://rosettacode.org/wiki/CSV_to_HTML_translation | CSV to HTML translation | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
Create a function that takes a string representation of the CSV data
and returns a text string of an HTML table representing the CSV data.
Use the following data as the CSV text to convert, and show your output.
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
Extra credit
Optionally allow special formatting for the first row of the table as if it is the tables header row
(via <thead> preferably; CSS if you must).
| #TXR | TXR | @(collect)
@char,@speech
@(end)
@(output :filter :to_html)
<table>
@ (repeat)
<tr>
<td>@char</td>
<td>@speech</td>
</tr>
@ (end)
</table>
@(end) |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
string 0; \use zero-terminated strings, instead of MSb terminated
func StrNCmp(A, B, N); \Compare string A to string B up to N bytes long
\This returns:
\ >0 if A > B
\ =0 if A = B
\ <0 if A < B
char A, B; \strings to be compared
int N; \number of bytes to compare
int I;
[for I:= 0 to N-1 do
if A(I) # B(I) then
return A(I) - B(I);
return 0; \they're equal
]; \StrNCmp
func StrLen(Str); \Return the number of characters in an ASCIIZ string
char Str;
int I;
for I:= 0 to -1>>1-1 do
if Str(I) = 0 then return I;
func SubStr(A, B); \Count number of times string B occurs in A
char A, B;
int LA, LB, C, I;
[LA:= StrLen(A); LB:= StrLen(B);
C:= 0; I:= 0;
while I < LA do
if StrNCmp(B, A+I, LB) = 0 then [C:= C+1; I:= I+LB]
else I:= I+1;
return C;
];
[IntOut(0, SubStr("the three truths", "th")); CrLf(0);
IntOut(0, SubStr("ababababab", "abab")); CrLf(0);
] |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #zkl | zkl | fcn countSubstring(s,p){ pn:=p.len(); cnt:=n:=0;
while(Void!=(n:=s.find(p,n))){cnt+=1; n+=pn}
cnt
} |
http://rosettacode.org/wiki/Copy_stdin_to_stdout | Copy stdin to stdout | Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
| #8086_Assembly | 8086 Assembly | READ: equ 3Fh ; MS-DOS syscalls
WRITE: equ 40h
BUFSZ: equ 4000h ; Buffer size
cpu 8086
bits 16
org 100h
section .text
read: mov ah,READ ; Read into buffer
xor bx,bx ; From STDIN (file 0)
mov cx,BUFSZ
mov dx,buffer
int 21h
test ax,ax ; Did we read anything?
jz done ; If not, stop
xchg ax,cx ; Write as many bytes as read
mov ah,WRITE
inc bx ; To STDOUT (file 1)
int 21h
jmp read ; Go get more
done: ret
section .bss
buffer: resb BUFSZ |
http://rosettacode.org/wiki/Create_an_HTML_table | Create an HTML table | Create an HTML table.
The table body should have at least three rows of three columns.
Each of these three columns should be labelled "X", "Y", and "Z".
An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less.
The numbers should be aligned in the same fashion for all columns.
| #Rascal | Rascal | import IO;
import util::Math;
str html(str title, str content) = item("html", item("title", title) + item("body", content));
str item(str op, str content) = "\<<op>\><content>\</<op>\>";
str table(str content) = item("table border=\"0\"", content);
str tr(str content) = item("tr", content);
str td(str content) = item("td", content);
public str generateTable(int rows){
int i(){return arbInt(10000);};
rows = (tr(td("")+td("X")+td("Y")+td("Z"))
| it + tr(td("<x>")+td("<i()>")+td("<i()>")+td("<i()>"))
| x <- [1..rows]);
writeFile(|file:///location|,
html("Rosetta Code Table", table(rows)));
return "written";
} |
http://rosettacode.org/wiki/CSV_to_HTML_translation | CSV to HTML translation | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
Create a function that takes a string representation of the CSV data
and returns a text string of an HTML table representing the CSV data.
Use the following data as the CSV text to convert, and show your output.
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
Extra credit
Optionally allow special formatting for the first row of the table as if it is the tables header row
(via <thead> preferably; CSS if you must).
| #UNIX_Shell | UNIX Shell | csv2html() {
IFS=,
echo "<table>"
echo "<thead>"
read -a fields
htmlrow th "${fields[@]}"
echo "</thead>"
echo "<tbody>"
while read -a fields
do htmlrow td "${fields[@]}"
done
echo "</tbody>"
echo "</table>"
}
htmlrow() {
cell=$1
shift
echo "<tr>"
for field
do echo "<$cell>$(escape_html "$field")</$cell>"
done
echo "</tr>"
}
escape_html() {
str=${1//\&/&}
str=${str//</<}
str=${str//>/>}
echo "$str"
}
csv2html <<-END
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
END |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer count.
print countSubstring("the three truths","th")
3
// do not count substrings that overlap with previously-counted substrings:
print countSubstring("ababababab","abab")
2
The matching should yield the highest number of non-overlapping matches.
In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page).
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 LET t$="ABABABABAB": LET p$="ABAB": GO SUB 1000
20 LET t$="THE THREE TRUTHS": LET p$="TH": GO SUB 1000
30 STOP
1000 PRINT t$: LET c=0
1010 LET lp=LEN p$
1020 FOR i=1 TO LEN t$-lp+1
1030 IF (t$(i TO i+lp-1)=p$) THEN LET c=c+1: LET i=i+lp-1
1040 NEXT i
1050 PRINT p$;"=";c''
1060 RETURN |
http://rosettacode.org/wiki/Copy_stdin_to_stdout | Copy stdin to stdout | Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
| #Action.21 | Action! | PROC Main()
CHAR c
DO
c=GetD(7)
Put(c)
UNTIL c=27 ;repeat until Esc key is pressed
OD
RETURN |
http://rosettacode.org/wiki/Copy_stdin_to_stdout | Copy stdin to stdout | Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
| #Ada | Ada | with Ada.Text_IO;
procedure Copy_Stdin_To_Stdout is
use Ada.Text_IO;
C : Character;
begin
while not End_Of_File loop
Get_Immediate (C);
Put (C);
end loop;
end Copy_Stdin_To_Stdout; |
http://rosettacode.org/wiki/Copy_stdin_to_stdout | Copy stdin to stdout | Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
| #Aime | Aime | file f;
data b;
f.stdin;
while (f.b_line(b) ^ -1) {
o_(b, "\n");
} |
http://rosettacode.org/wiki/Copy_stdin_to_stdout | Copy stdin to stdout | Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
| #ALGOL_68 | ALGOL 68 | BEGIN
BOOL at eof := FALSE;
# set the EOF handler for stand in to a procedure that sets "at eof" to true #
# and returns true so processing can continue #
on logical file end( stand in, ( REF FILE f )BOOL: at eof := TRUE );
# copy stand in to stand out #
WHILE STRING line; read( ( line, newline ) ); NOT at eof DO write( ( line, newline ) ) OD
END |
http://rosettacode.org/wiki/Create_an_HTML_table | Create an HTML table | Create an HTML table.
The table body should have at least three rows of three columns.
Each of these three columns should be labelled "X", "Y", and "Z".
An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less.
The numbers should be aligned in the same fashion for all columns.
| #Red | Red |
Create an HTML table
The table body should have at least three rows of three columns.
Each of these three columns should be labelled "X", "Y", and "Z".
An extra column should be added at either the extreme left or the extreme right
of the table that has no heading, but is filled with sequential row numbers.
The rows of the "X", "Y", and "Z" columns should be filled with random or
sequential integers having 4 digits or less.
The numbers should be aligned in the same fashion for all columns.
Red [
Problem: %http://www.rosettacode.org/wiki/Create_an_HTML_table
Code: %https://github.com/metaperl/red-rosetta/blob/master/html-table.r
Acknowledgements: "@endo64 @toomsav"
]
result: func[][simple-tag "table" trs]
trs: func [][rejoin [
first-tr
rand-tr 1
rand-tr 2
rand-tr 3
rand-tr 4
rand-tr 5
]]
table-data: func [][999 + (random 9000)]
rand-td: func [][simple-tag "td" table-data]
rand-tr: func [i][rejoin [
simple-tag "tr"
rejoin [(simple-tag "td" i) rand-td rand-td rand-td]
]]
first-tr: func[][rejoin [
simple-tag "tr" rejoin [
simple-tag "th" ""
simple-tag "th" "X"
simple-tag "th" "Y"
simple-tag "th" "Z"
]
]]
simple-tag: func [tag contents /attr a][rejoin
["<" tag (either attr [rejoin [" " a/1 "=" {"} a/2 {"}]][]) ">"
newline contents newline "</" tag ">"]]
|
http://rosettacode.org/wiki/CSV_to_HTML_translation | CSV to HTML translation | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
Create a function that takes a string representation of the CSV data
and returns a text string of an HTML table representing the CSV data.
Use the following data as the CSV text to convert, and show your output.
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
Extra credit
Optionally allow special formatting for the first row of the table as if it is the tables header row
(via <thead> preferably; CSS if you must).
| #VBA | VBA | Public Sub CSV_TO_HTML()
input_ = "Character,Speech\n" & _
"The multitude,The messiah! Show us the messiah!\n" & _
"Brians mother,<angry>Now you listen here! He's not the messiah; " & _
"he's a very naughty boy! Now go away!</angry>\n" & _
"The multitude,Who are you?\n" & _
"Brians mother,I'm his mother; that's who!\n" & _
"The multitude,Behold his mother! Behold his mother!"
Debug.Print "<table>" & vbCrLf & "<tr><td>"
For i = 1 To Len(input_)
Select Case Mid(input_, i, 1)
Case "\"
If Mid(input_, i + 1, 1) = "n" Then
Debug.Print "</td></tr>" & vbCrLf & "<tr><td>";
i = i + 1
Else
Debug.Print Mid(input_, i, 1);
End If
Case ",": Debug.Print "</td><td>";
Case "<": Debug.Print "<";
Case ">": Debug.Print ">";
Case "&": Debug.Print "&";
Case Else: Debug.Print Mid(input_, i, 1);
End Select
Next i
Debug.Print "</td></tr>" & vbCrLf & "</table>"
End Sub |
http://rosettacode.org/wiki/Copy_stdin_to_stdout | Copy stdin to stdout | Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
| #Applesoft_BASIC | Applesoft BASIC | 0 GET C$ : PRINT C$; : GOTO |
http://rosettacode.org/wiki/Copy_stdin_to_stdout | Copy stdin to stdout | Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
| #AWK | AWK | awk "//" |
http://rosettacode.org/wiki/Copy_stdin_to_stdout | Copy stdin to stdout | Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
| #BCPL | BCPL | get "libhdr"
let start() be
$( let c = rdch()
if c = endstreamch then finish
wrch(c)
$) repeat |
http://rosettacode.org/wiki/Copy_stdin_to_stdout | Copy stdin to stdout | Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
| #Brainf.2A.2A.2A | Brainf*** | ,[.,] |
http://rosettacode.org/wiki/Create_an_HTML_table | Create an HTML table | Create an HTML table.
The table body should have at least three rows of three columns.
Each of these three columns should be labelled "X", "Y", and "Z".
An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less.
The numbers should be aligned in the same fashion for all columns.
| #Retro | Retro | needs casket::html'
with casket::html'
: rnd ( -$ ) random 1000 mod toString ;
[ [ [ ] td [ "x" ] td [ "y" ] td [ "z" ] td ] tr
[ [ "1" ] td [ rnd ] td [ rnd ] td [ rnd ] td ] tr
[ [ "2" ] td [ rnd ] td [ rnd ] td [ rnd ] td ] tr
[ [ "3" ] td [ rnd ] td [ rnd ] td [ rnd ] td ] tr
[ [ "4" ] td [ rnd ] td [ rnd ] td [ rnd ] td ] tr
[ [ "5" ] td [ rnd ] td [ rnd ] td [ rnd ] td ] tr
[ [ "6" ] td [ rnd ] td [ rnd ] td [ rnd ] td ] tr
] table |
http://rosettacode.org/wiki/CSV_to_HTML_translation | CSV to HTML translation | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
Create a function that takes a string representation of the CSV data
and returns a text string of an HTML table representing the CSV data.
Use the following data as the CSV text to convert, and show your output.
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
Extra credit
Optionally allow special formatting for the first row of the table as if it is the tables header row
(via <thead> preferably; CSS if you must).
| #VBScript | VBScript |
Set objfso = CreateObject("Scripting.FileSystemObject")
parent_folder = objfso.GetParentFolderName(WScript.ScriptFullName) & "\"
Set objcsv = objfso.OpenTextFile(parent_folder & "in.csv",1,False)
Set objhtml = objfso.OpenTextFile(paren_folder & "out.html",2,True)
objhtml.Write(csv_to_html(objcsv.ReadAll))
objcsv.Close
objhtml.Close
Set objfso = Nothing
Function csv_to_html(s)
row = Split(s,vbCrLf)
'write the header
tmp = "<html><head><head/><body><table border=1 cellpadding=10 cellspacing=0>"
For i = 0 To UBound(row)
field = Split(row(i),",")
If i = 0 Then
tmp = tmp & "<tr><th>" & replace_chars(field(0)) & "</th><th>" & replace_chars(field(1)) & "</th><tr>"
Else
tmp = tmp & "<tr><td>" & replace_chars(field(0)) & "</td><td>" & replace_chars(field(1)) & "</td><tr>"
End If
Next
'write the footer
tmp = tmp & "</table></body></html>"
csv_to_html = tmp
End Function
Function replace_chars(s)
replace_chars = Replace(Replace(s,"<","<"),">",">")
End Function
|
http://rosettacode.org/wiki/Copy_stdin_to_stdout | Copy stdin to stdout | Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
| #C | C |
#include <stdio.h>
int main(){
char c;
while ( (c=getchar()) != EOF ){
putchar(c);
}
return 0;
}
|
http://rosettacode.org/wiki/Copy_stdin_to_stdout | Copy stdin to stdout | Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
| #C.23 | C# |
using System;
class Program
{
static void Main(string[] args)
{
Console.OpenStandardInput().CopyTo(Console.OpenStandardOutput());
}
}
|
http://rosettacode.org/wiki/Copy_stdin_to_stdout | Copy stdin to stdout | Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
| #C.2B.2B | C++ | #include <iostream>
#include <iterator>
int main() {
using namespace std;
noskipws(cin);
copy(
istream_iterator<char>(cin),
istream_iterator<char>(),
ostream_iterator<char>(cout)
);
return 0;
} |
http://rosettacode.org/wiki/Create_an_HTML_table | Create an HTML table | Create an HTML table.
The table body should have at least three rows of three columns.
Each of these three columns should be labelled "X", "Y", and "Z".
An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less.
The numbers should be aligned in the same fashion for all columns.
| #REXX | REXX | /*REXX program creates (and displays) an HTML table of five rows and three columns.*/
parse arg rows . /*obtain optional argument from the CL.*/
if rows=='' | rows=="," then rows=5 /*no ROWS specified? Then use default.*/
cols = 3 /*specify three columns for the table. */
maxRand = 9999 /*4-digit numbers, allows negative nums*/
headerInfo = 'X Y Z' /*specifify column header information. */
oFID = 'a_table.html' /*name of the output file. */
w = 0 /*number of writes to the output file. */
call wrt "<html>"
call wrt "<head></head>"
call wrt "<body>"
call wrt "<table border=5 cellpadding=20 cellspace=0>"
do r=0 to rows /* [↓] handle row 0 as being special.*/
if r==0 then call wrt "<tr><th></th>" /*when it's the zeroth row. */
else call wrt "<tr><th>" r "</th>" /* " " not " " " */
do c=1 for cols /* [↓] for row 0, add the header info*/
if r==0 then call wrt "<th>" word(headerInfo,c) "</th>"
else call wrt "<td align=right>" rnd() "</td>"
end /*c*/
end /*r*/
call wrt "</table>"
call wrt "</body>"
call wrt "</html>"
say; say w ' records were written to the output file: ' oFID
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
rnd: return right(random(0,maxRand*2)-maxRand,5) /*RANDOM doesn't generate negative ints*/
wrt: call lineout oFID,arg(1); say '══►' arg(1); w=w+1; return /*write.*/ |
http://rosettacode.org/wiki/CSV_to_HTML_translation | CSV to HTML translation | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
Create a function that takes a string representation of the CSV data
and returns a text string of an HTML table representing the CSV data.
Use the following data as the CSV text to convert, and show your output.
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
Extra credit
Optionally allow special formatting for the first row of the table as if it is the tables header row
(via <thead> preferably; CSS if you must).
| #Vedit_macro_language | Vedit macro language | if (BB < 0) { // block not set
BB(0) // convert entire file
BE(File_Size)
}
// Convert special characters into entities
Replace_Block("&","&", BB, BE, BEGIN+ALL+NOERR)
Replace_Block("<","<", BB, BE, BEGIN+ALL+NOERR)
Replace_Block(">",">", BB, BE, BEGIN+ALL+NOERR)
// Convert CSV into HTML table
Goto_Pos(BB)
IT('<table>') IN
#80 = Cur_Pos
Goto_Pos(BE)
IT("</table>")
#81 = Cur_Line
IN
Goto_Pos(#80)
while (Cur_Line < #81) {
IT(" <tr><td>")
Replace_Block(",","</td><td>",Cur_Pos,EOL_Pos,ALL+NOERR)
EOL
IT("</td></tr>")
Line(1)
}
BB(Clear) |
http://rosettacode.org/wiki/Copy_stdin_to_stdout | Copy stdin to stdout | Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
| #CLU | CLU | start_up = proc ()
pi: stream := stream$primary_input()
po: stream := stream$primary_output()
while true do
stream$putc(po, stream$getc(pi))
end except when end_of_file:
return
end
end start_up |
http://rosettacode.org/wiki/Copy_stdin_to_stdout | Copy stdin to stdout | Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
| #Commodore_BASIC | Commodore BASIC | 10 print chr$(147);chr$(14);
11 print "0:Keyboard 1:Tape 2:RS-232 3:Screen"
12 print "4-7:printers/plotters"
13 print "8-11:Disk Drives":print
14 input "Input device";d1
15 if d1=1 or d1>=8 then input "Filename for INPUT";i$
16 input "Output device";d2
17 if d2=1 or d2>=8 then input "Filename for OUTPUT";o$
18 print:if d1=0 then print "Begin typing. Press CTRL-Z to end.":print
20 open 5,d1,5,"0:"+i$+",s,r"
30 open 2,d2,2,"@0:"+o$+",s,w"
40 get#5,a$
50 if (d1=0 and a$=chr$(26)) or (d1>0 and st>0) then close 5:close 2:end
60 print#2,a$;
70 goto 40 |
http://rosettacode.org/wiki/Copy_stdin_to_stdout | Copy stdin to stdout | Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
| #Common_Lisp | Common Lisp | #|Loops while reading and collecting characters from STDIN until EOF (C-Z or C-D)
Then concatenates the characters into a string|#
(format t
(concatenate 'string
(loop for x = (read-char *query-io*) until (or (char= x #\Sub) (char= x #\Eot)) collecting x)))
|
http://rosettacode.org/wiki/Create_an_HTML_table | Create an HTML table | Create an HTML table.
The table body should have at least three rows of three columns.
Each of these three columns should be labelled "X", "Y", and "Z".
An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less.
The numbers should be aligned in the same fashion for all columns.
| #Ring | Ring |
# Project: Create an HTML table
load "stdlib.ring"
str = ""
ncols = 3
nrows = 4
str = str + "<html><head></head><body>" + windowsnl()
str = str + "<table border=1 cellpadding=10 cellspacing=0>" + windowsnl()
for row = 0 to nrows
if row = 0
str = str + "<tr><th></th>"
else
str = str + "<tr><th>" + row + "</th>"
ok
for col = 1 to ncols
if row = 0
str = str + "<th>" + char(87 + col) + "</th>"
else
str = str + "<td align=" + '"right"' + ">" + random(9999) + "</td>"
ok
next
str = str + windowsnl() + "</tr>" +windowsnl()
next
str = str + "</table>" + windowsnl()
str = str + "</body></html>" + windowsnl()
remove("temp.htm")
write("temp.htm",str)
see str + nl
systemcmd("temp.htm")
|
http://rosettacode.org/wiki/CSV_to_HTML_translation | CSV to HTML translation | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
Create a function that takes a string representation of the CSV data
and returns a text string of an HTML table representing the CSV data.
Use the following data as the CSV text to convert, and show your output.
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
Extra credit
Optionally allow special formatting for the first row of the table as if it is the tables header row
(via <thead> preferably; CSS if you must).
| #Visual_Basic_.NET | Visual Basic .NET | Imports Microsoft.VisualBasic.FileIO
Module Program
Sub Main(args As String())
Dim parser As TextFieldParser
Try
If args.Length > 1 Then
parser = My.Computer.FileSystem.OpenTextFieldParser(args(1), ",")
Else
parser = New TextFieldParser(Console.In) With {.Delimiters = {","}}
End If
Dim getLines =
Iterator Function() As IEnumerable(Of String())
Do Until parser.EndOfData
Yield parser.ReadFields()
Loop
End Function
Dim result = CSVTOHTML(getLines(), If(args.Length > 0, Boolean.Parse(args(0)), False))
Console.WriteLine(result)
Finally
If parser IsNot Nothing Then parser.Dispose()
End Try
End Sub
Function CSVTOHTML(lines As IEnumerable(Of IEnumerable(Of String)), useTHead As Boolean) As XElement
Dim getRow = Function(row As IEnumerable(Of String)) From field In row Select <td><%= field %></td>
CSVTOHTML =
<table>
<%= From l In lines.Select(
Function(line, i)
If useTHead AndAlso i = 0 Then
Return <thead><%= getRow(line) %></thead>
Else
Return <tr><%= getRow(line) %></tr>
End If
End Function) %>
</table>
End Function
End Module |
http://rosettacode.org/wiki/Copy_stdin_to_stdout | Copy stdin to stdout | Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
| #Crystal | Crystal | STDIN.each_line do |line|
puts line
end |
http://rosettacode.org/wiki/Copy_stdin_to_stdout | Copy stdin to stdout | Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
| #D | D | import std.stdio;
void main() {
foreach (line; stdin.byLine) {
writeln(line);
}
} |
http://rosettacode.org/wiki/Copy_stdin_to_stdout | Copy stdin to stdout | Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
| #Dart | Dart | import 'dart:io';
void main() {
var line = stdin.readLineSync();
stdout.write(line);
} |
http://rosettacode.org/wiki/Copy_stdin_to_stdout | Copy stdin to stdout | Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
| #Delphi | Delphi | \util.g
proc nonrec main() void:
char c;
while
/* I/O is line-oriented, so first read characters
* from the current line while that is possible */
while read(c) do write(c) od;
case ioerror()
/* Then once it fails, if the line is empty,
* try to go to the next line. */
incase CH_MISSING:
readln();
writeln();
true
/* If it failed for another reason (which will be
* EOF here), stop. */
default:
false
esac
do od
corp |
http://rosettacode.org/wiki/Create_an_HTML_table | Create an HTML table | Create an HTML table.
The table body should have at least three rows of three columns.
Each of these three columns should be labelled "X", "Y", and "Z".
An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less.
The numbers should be aligned in the same fashion for all columns.
| #Ruby | Ruby |
def r
rand(10000)
end
STDOUT << "".tap do |html|
html << "<table>"
[
['X', 'Y', 'Z'],
[r ,r ,r],
[r ,r ,r],
[r ,r ,r],
[r ,r ,r]
].each_with_index do |row, index|
html << "<tr>"
html << "<td>#{index > 0 ? index : nil }</td>"
html << row.map { |e| "<td>#{e}</td>"}.join
html << "</tr>"
end
html << "</table>"
end
|
http://rosettacode.org/wiki/CSV_to_HTML_translation | CSV to HTML translation | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
Create a function that takes a string representation of the CSV data
and returns a text string of an HTML table representing the CSV data.
Use the following data as the CSV text to convert, and show your output.
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
Extra credit
Optionally allow special formatting for the first row of the table as if it is the tables header row
(via <thead> preferably; CSS if you must).
| #Wren | Wren | var csv =
"Character,Speech\n" +
"The multitude,The messiah! Show us the messiah!\n" +
"Brians mother,<angry>Now you listen here! He's not the messiah; " +
"he's a very naughty boy! Now go away!</angry>\n" +
"The multitude,Who are you?\n" +
"Brians mother,I'm his mother; that's who!\n" +
"The multitude,Behold his mother! Behold his mother!"
var i = " " // indent
var ii = i + i // double indent
var iii = ii + i // triple indent
var sb = "<table>\n%(i)<tr>\n%(ii)<td>"
for (c in csv) {
sb = sb + ((c == "\n") ? "</td>\n%(i)</tr>\n%(i)<tr>\n%(ii)<td>" :
(c == ",") ? "</td>\n%(ii)<td>" :
(c == "&") ? "&" :
(c == "'") ? "'" :
(c == "<") ? "<" :
(c == ">") ? ">" : c)
}
sb = sb + "</td>\n%(i)</tr>\n</table>"
System.print(sb)
System.print()
// now using first row as a table header
sb = "<table>\n%(i)<thead>\n%(ii)<tr>\n%(iii)<td>"
var hLength = csv.indexOf("\n") + 1 // find length of first row including CR
for (c in csv.take(hLength)) {
sb = sb + ((c == "\n") ? "</td>\n%(ii)</tr>\n%(i)</thead>\n%(i)<tbody>\n%(ii)<tr>\n%(iii)<td>" :
(c == ",") ? "</td>\n%(iii)<td>" : c)
}
for (c in csv.skip(hLength)) {
sb = sb + ((c == "\n") ? "</td>\n%(ii)</tr>\n%(ii)<tr>\n%(iii)<td>" :
(c == ",") ? "</td>\n%(iii)<td>" :
(c == "&") ? "&" :
(c == "'") ? "'" :
(c == "<") ? "<" :
(c == ">") ? ">" : c)
}
sb = sb + "</td>\n%(ii)</tr>\n%(i)</tbody>\n</table>"
System.print(sb) |
http://rosettacode.org/wiki/Copy_stdin_to_stdout | Copy stdin to stdout | Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
| #Draco | Draco | \util.g
proc nonrec main() void:
char c;
while
/* I/O is line-oriented, so first read characters
* from the current line while that is possible */
while read(c) do write(c) od;
case ioerror()
/* Then once it fails, if the line is empty,
* try to go to the next line. */
incase CH_MISSING:
readln();
writeln();
true
/* If it failed for another reason (which will be
* EOF here), stop. */
default:
false
esac
do od
corp |
http://rosettacode.org/wiki/Copy_stdin_to_stdout | Copy stdin to stdout | Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
| #F.23 | F# |
let copy()=let n,g=stdin,stdout
let rec fN()=match n.ReadLine() with "EOF"->g.Write "" |i->g.WriteLine i; fN()
fN()
copy()
|
http://rosettacode.org/wiki/Copy_stdin_to_stdout | Copy stdin to stdout | Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
| #Factor | Factor | USING: io kernel ;
[ read1 dup ] [ write1 ] while drop |
http://rosettacode.org/wiki/Copy_stdin_to_stdout | Copy stdin to stdout | Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
| #Forth | Forth | stdin slurp-fid type bye |
http://rosettacode.org/wiki/Create_an_HTML_table | Create an HTML table | Create an HTML table.
The table body should have at least three rows of three columns.
Each of these three columns should be labelled "X", "Y", and "Z".
An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less.
The numbers should be aligned in the same fashion for all columns.
| #Run_BASIC | Run BASIC | html "<table border=1><tr align=center><td>Row</td><td>X</td><td>Y</td><td>Z</td></tr>"
for i = 1 to 5
html "<tr align=right>"
for j = 1 to 4
if j = 1 then html "<td>";i;"</td>" else html "<td>";i;j;"</td>"
next j
html "</tr>"
next i
html "</table>" |
http://rosettacode.org/wiki/CSV_to_HTML_translation | CSV to HTML translation | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
Create a function that takes a string representation of the CSV data
and returns a text string of an HTML table representing the CSV data.
Use the following data as the CSV text to convert, and show your output.
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
Extra credit
Optionally allow special formatting for the first row of the table as if it is the tables header row
(via <thead> preferably; CSS if you must).
| #XSLT_2.0 | XSLT 2.0 | <xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xcsvt="http://www.seanbdurkin.id.au/xslt/csv-to-xml.xslt"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xcsv="http://www.seanbdurkin.id.au/xslt/xcsv.xsd"
version="2.0"
exclude-result-prefixes="xsl xs xcsvt xcsv">
<xsl:import href="csv-to-xml.xslt" />
<xsl:output indent="yes" encoding="UTF-8" method="html" doctype-system="about:legacy-compat" />
<xsl:import-schema schema-location="http://www.seanbdurkin.id.au/xslt/xcsv.xsd"
use-when="system-property('xsl:is-schema-aware')='yes'" />
<xsl:param name="url-of-csv" as="xs:string" select="'roseta.csv'" />
<xsl:variable name="phase-1-result">
<xsl:call-template name="xcsvt:main" />
</xsl:variable>
<xsl:template match="/">
<html lang="en">
<head><title>CSV to HTML translation - Extra Credit</title></head>
<body>
<xsl:apply-templates select="$phase-1-result" mode="phase-2" />
</body>
</html>
</xsl:template>
<xsl:template match="xcsv:comma-separated-single-line-values" mode="phase-2">
<table>
<xsl:apply-templates mode="phase-2" />
</table>
</xsl:template>
<xsl:template match="xcsv:row[1]" mode="phase-2">
<th>
<xsl:apply-templates mode="phase-2" />
</th>
</xsl:template>
<xsl:template match="xcsv:row" mode="phase-2">
<tr>
<xsl:apply-templates mode="phase-2" />
</tr>
</xsl:template>
<xsl:template match="xcsv:value" mode="phase-2">
<td>
<xsl:apply-templates mode="phase-2" />
</td>
</xsl:template>
<xsl:template match="xcsv:notice" mode="phase-2" />
</xsl:stylesheet> |
http://rosettacode.org/wiki/Copy_stdin_to_stdout | Copy stdin to stdout | Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
| #FreeBASIC | FreeBASIC | #define FIN 255 'eof is already a reserved word
#include "crt/stdio.bi" 'provides the C functions getchar and putchar
dim as ubyte char
do
char = getchar()
if char = FIN then exit do else putchar(char)
loop |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.