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/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. Fo...
#Elixir
Elixir
iex(1)> URI.encode("http://foo bar/", &URI.char_unreserved?/1) "http%3A%2F%2Ffoo%20bar%2F"
http://rosettacode.org/wiki/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. Fo...
#Erlang
Erlang
1> http_uri:encode("http://foo bar/"). "http%3A%2F%2Ffoo%20bar%2F"
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#DM
DM
// Both of the following declarations can be seen as a tree, // var -> <varname> var/x var y   // They can also be defined like this. // This is once again a tree structure, but this time the "var" only appears once, and the x and y are children. var x y // And like this, still a tree structure. var/x, y  
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#Diego
Diego
add_var(v1); dim(v1); add_var(v1, v2, v3, v4); dim(v1, v2, v3, v4); add_var(isRaining)_datatype(boolean); dim(isRaining)_datatype(boolean); add_var(greeting)_dt(string); dim(greeting)_dt(string); add_var({date}, birthdate); dim({date}, birthdate);
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using ...
#Go
Go
package main   import "fmt"   func main() { const max = 1000 a := make([]int, max) // all zero by default for n := 0; n < max-1; n++ { for m := n - 1; m >= 0; m-- { if a[m] == a[n] { a[n+1] = n - m break } } } fmt.Println("...
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using ...
#Haskell
Haskell
import Data.List (elemIndex) import Data.Maybe (maybe)   vanEck :: Int -> [Int] vanEck n = reverse $ iterate go [] !! n where go [] = [0] go xxs@(x:xs) = maybe 0 succ (elemIndex x xs) : xxs   main :: IO () main = do print $ vanEck 10 print $ drop 990 (vanEck 1000)
http://rosettacode.org/wiki/Vampire_number
Vampire number
A vampire number is a natural decimal number with an even number of digits,   that can be factored into two integers. These two factors are called the   fangs,   and must have the following properties:   they each contain half the number of the decimal digits of the original number   together they consist of exactl...
#Perl
Perl
#!/usr/bin/perl use warnings; use strict; use feature qw(say);   sub fangs { my $vampire = shift; my $length = length 0 + $vampire; return if $length % 2; my $fang_length = $length / 2; my $from = '1' . '0' x ($fang_length - 1); my $to = '9' x $fang_length; my $sorted =...
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function...
#Lua
Lua
function varar(...) for i, v in ipairs{...} do print(v) end end
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function...
#M2000_Interpreter
M2000 Interpreter
  Module CheckIt { \\ Works for numbers and strings (letters in M2000) Function Variadic { \\ print a letter for each type in function stack Print Envelope$() \\Check types using Match Print Match("NNSNNS") =stack.size While not Empty {...
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to...
#Rust
Rust
use std::fmt; use std::ops::{Add, Div, Mul, Sub};   #[derive(Copy, Clone, Debug)] pub struct Vector<T> { pub x: T, pub y: T, }   impl<T> fmt::Display for Vector<T> where T: fmt::Display, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if let Some(prec) = f.precision() { writ...
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to...
#Scala
Scala
object Vector extends App {   case class Vector2D(x: Double, y: Double) { def +(v: Vector2D) = Vector2D(x + v.x, y + v.y)   def -(v: Vector2D) = Vector2D(x - v.x, y - v.y)   def *(s: Double) = Vector2D(s * x, s * y)   def /(s: Double) = Vector2D(x / s, y / s)   override def toString() = s"Vector($...
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher
Vigenère cipher
Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) Related tasks   Caesar ...
#Rust
Rust
use std::ascii::AsciiExt;   static A: u8 = 'A' as u8;   fn uppercase_and_filter(input: &str) -> Vec<u8> { let alphabet = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; let mut result = Vec::new();   for c in input.chars() { // Ignore anything that is not in our short list of chars. We can ...
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher
Vigenère cipher
Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) Related tasks   Caesar ...
#Scala
Scala
  object Vigenere { def encrypt(msg: String, key: String) : String = { var result: String = "" var j = 0   for (i <- 0 to msg.length - 1) { val c = msg.charAt(i) if (c >= 'A' && c <= 'Z') { result += ((c + key.charAt(j) - 2 * 'A') % 26 + 'A').toChar j = (j + 1) % key.length ...
http://rosettacode.org/wiki/Vector_products
Vector products
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numbers,   (X, Y, Z)   would repr...
#ERRE
ERRE
  PROGRAM VECTORPRODUCT   !$DOUBLE   TYPE TVECTOR=(X,Y,Z)   DIM A:TVECTOR,B:TVECTOR,C:TVECTOR   DIM AA:TVECTOR,BB:TVECTOR,CC:TVECTOR DIM DD:TVECTOR,EE:TVECTOR,FF:TVECTOR   PROCEDURE DOTPRODUCT(DD.,EE.->DOTP) DOTP=DD.X*EE.X+DD.Y*EE.Y+DD.Z*EE.Z END PROCEDURE   PROCEDURE CROSSPRODUCT(DD.,EE.->FF.) FF.X=DD.Y*EE.Z-DD....
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number
Validate International Securities Identification Number
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct format,   and   the embedded c...
#Kotlin
Kotlin
// version 1.1   object Isin { val r = Regex("^[A-Z]{2}[A-Z0-9]{9}[0-9]$")   fun isValid(s: String): Boolean { // check format if (!s.matches(r)) return false // validate checksum val sb = StringBuilder() for (c in s) { when (c) { in '0'..'9' -...
http://rosettacode.org/wiki/Van_der_Corput_sequence
Van der Corput sequence
When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 {\displaystyle 2^{1}} ; and so o...
#Haskell
Haskell
import Data.Ratio (Rational(..), (%), numerator, denominator) import Data.List (unfoldr) import Text.Printf (printf)   -- A wrapper type for Rationals to make them look nicer when we print them. newtype Rat = Rat Rational   instance Show Rat where show (Rat n) = show (numerator n) <> ('/' : show (denominator n))   ...
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   Th...
#CoffeeScript
CoffeeScript
  console.log decodeURIComponent "http%3A%2F%2Ffoo%20bar%2F?name=Foo%20Barson"  
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   Th...
#Common_Lisp
Common Lisp
(defun decode (string &key start) (assert (char= (char string start) #\%)) (if (>= (length string) (+ start 3)) (multiple-value-bind (code pos) (parse-integer string :start (1+ start) :end (+ start 3) :radix 16 :junk-allowed t) (if (= pos (+ start 3)) (values (code-char code) pos...
http://rosettacode.org/wiki/UPC
UPC
Goal Convert UPC bar codes to decimal. Specifically: The UPC standard is actually a collection of standards -- physical standards, data format standards, product reference standards... Here,   in this task,   we will focus on some of the data format standards,   with an imaginary physical+electrical implementati...
#Action.21
Action!
DEFINE PTR="CARD" DEFINE RESOK="255" DEFINE RESUPSIDEDOWN="254" DEFINE RESINVALID="253" DEFINE DIGITCOUNT="12" DEFINE DIGITLEN="7"   PTR ARRAY ldigits(10),rdigits(10) CHAR ARRAY marker="# #",midmarker=" # # "   PROC Init() ldigits(0)=" ## #" ldigits(1)=" ## #" ldigits(2)=" # ##" ldigits(3)=" #### #" ldigits...
http://rosettacode.org/wiki/Update_a_configuration_file
Update a configuration file
We have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines begininning with a hash or a semicolon are ignored by the application # program. Blank lines are also ignored by the application program. # The first word on each non comment line is the configurati...
#Erlang
Erlang
  -module( update_configuration_file ).   -export( [add/3, change/3, disable/2, enable/2, read/1, task/0, write/2] ).   add( Option, Value, Lines ) -> Upper = string:to_upper( Option ), [string:join( [Upper, Value], " " ) | Lines].   change( Option, Value, Lines ) -> Upper = string:to_upper( Option ), change_done( ...
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#C.23
C#
using System;   namespace C_Sharp_Console {   class example {   static void Main() { string word; int num;   Console.Write("Enter an integer: "); num = Console.Read(); Console.Write("Enter a String: "); word = Console.ReadLine(); ...
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#C.2B.2B
C++
#include <iostream> #include <string> using namespace std;   int main() { // while probably all current implementations have int wide enough for 75000, the C++ standard // only guarantees this for long int. long int integer_input; string string_input; cout << "Enter an integer: "; cin >> ...
http://rosettacode.org/wiki/User_input/Graphical
User input/Graphical
In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
#Delphi
Delphi
program UserInputGraphical;   {$APPTYPE CONSOLE}   uses SysUtils, Dialogs;   var s: string; lStringValue: string; lIntegerValue: Integer; begin lStringValue := InputBox('User input/Graphical', 'Enter a string', '');   repeat s := InputBox('User input/Graphical', 'Enter the number 75000', '75000'); lIn...
http://rosettacode.org/wiki/UTF-8_encode_and_decode
UTF-8 encode and decode
As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets. The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the...
#F.23
F#
  // Unicode character point to UTF8. Nigel Galloway: March 19th., 2018 let fN g = match List.findIndex (fun n->n>g) [0x80;0x800;0x10000;0x110000] with |0->[g] |1->[0xc0+(g&&&0x7c0>>>6);0x80+(g&&&0x3f)] |2->[0xe0+(g&&&0xf000>>>12);0x80+(g&&&0xfc0>>>6);0x80+(g&&&0x3f)] |_->[0x...
http://rosettacode.org/wiki/Use_another_language_to_call_a_function
Use another language to call a function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (i...
#Ol
Ol
  #include <extensions/embed.h>   #define min(x,y) (x < y ? x : y)   extern unsigned char repl[]; int Query(char *Data, size_t *Length) { ol_t ol; embed_new(&ol, repl, 0);   word s = embed_eval(&ol, new_string(&ol, "(define sample \"Here am I\")" "sample" ), 0); if (!is_string(s)) goto fail;   int i = *Leng...
http://rosettacode.org/wiki/Use_another_language_to_call_a_function
Use another language to call a function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (i...
#PARI.2FGP
PARI/GP
Strchr(Vecsmall(apply(k->if(k>96&&k<123,(k-84)%26+97,if(k>64&&k<91,(k-52)%26+65,k)),Vec(Vecsmall(s)))))
http://rosettacode.org/wiki/URL_parser
URL parser
URLs are strings with a simple syntax: scheme://[username:password@]domain[:port]/path?query_string#fragment_id Task Parse a well-formed URL to retrieve the relevant information:   scheme, domain, path, ... Note:   this task has nothing to do with URL encoding or URL decoding. According to the standards, t...
#Lua
Lua
local url = require('socket.url')   local tests = { 'foo://example.com:8042/over/there?name=ferret#nose', 'urn:example:animal:ferret:nose', 'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true', 'ftp://ftp.is.co.za/rfc/rfc1808.txt', 'http://www.ietf.org/rfc/rfc2396.txt#header1', 'ldap://...
http://rosettacode.org/wiki/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. Fo...
#F.23
F#
open System   [<EntryPoint>] let main args = printfn "%s" (Uri.EscapeDataString(args.[0])) 0
http://rosettacode.org/wiki/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. Fo...
#Factor
Factor
USING: combinators.short-circuit unicode urls.encoding.private ;   : my-url-encode ( str -- encoded ) [ { [ alpha? ] [ "-._~" member? ] } 1|| ] (url-encode) ;   "http://foo bar/" my-url-encode print
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#DWScript
DWScript
  var i := 123; // inferred type of i is Integer var s := 'abc'; // inferred type of s is String var o := TObject.Create; // inferred type of o is TObject var s2 := o.ClassName; // inferred type of s2 is String as that's the type returned by ClassName  
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#Dyalect
Dyalect
//A constant declaration let pi = 3.14   private { //private constant, not visible outside of a module let privateConst = 3.3 }   //Variable declaration var x = 42   //Assignment x = 42.42   //Dyalect is a dynamic language, so types are attached //to values, not to the names var foo = (x: 2, y: 4) //foo is of t...
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using ...
#J
J
VanEck=. (, (<:@:# - }: i: {:))^:(]`0:)
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using ...
#Java
Java
  import java.util.HashMap; import java.util.Map;   public class VanEckSequence {   public static void main(String[] args) { System.out.println("First 10 terms of Van Eck's sequence:"); vanEck(1, 10); System.out.println(""); System.out.println("Terms 991 to 1000 of Van Eck's sequence...
http://rosettacode.org/wiki/Vampire_number
Vampire number
A vampire number is a natural decimal number with an even number of digits,   that can be factored into two integers. These two factors are called the   fangs,   and must have the following properties:   they each contain half the number of the decimal digits of the original number   together they consist of exactl...
#Phix
Phix
with javascript_semantics requires("1.0.2") -- (for in) function vampire(atom v) sequence res = {} if v>=0 then string vs = sprintf("%d",v) if mod(length(vs),2)=0 then -- even length vs = sort(vs) for i=power(10,length(vs)/2-1) to floor(sqrt(v)) do if rema...
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function...
#M4
M4
define(`showN', `ifelse($1,0,`',`$2 $0(decr($1),shift(shift($@)))')')dnl define(`showargs',`showN($#,$@)')dnl dnl showargs(a,b,c) dnl define(`x',`1,2') define(`y',`,3,4,5') showargs(x`'y)
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ShowMultiArg[x___] := Do[Print[i], {i, {x}}]
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function...
#MATLAB
MATLAB
function variadicFunction(varargin)   for i = (1:numel(varargin)) disp(varargin{i}); end   end
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to...
#Sidef
Sidef
class MyVector(:args) {   has Number x has Number y   method init { if ([:x, :y] ~~ args) { x = args{:x} y = args{:y} } elsif ([:length, :angle] ~~ args) { x = args{:length}*args{:angle}.cos y = args{:length}*args{:angle}.sin } ...
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher
Vigenère cipher
Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) Related tasks   Caesar ...
#Seed7
Seed7
$ include "seed7_05.s7i";   const func string: vigenereCipher (in string: source, in var string: keyword) is func result var string: dest is ""; local var char: ch is ' '; var integer: index is 1; var integer: shift is 0; begin keyword := upper(keyword); for ch range source do if ch ...
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher
Vigenère cipher
Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) Related tasks   Caesar ...
#Sidef
Sidef
func s2v(s) { s.uc.scan(/[A-Z]/).map{.ord} »-» 65 } func v2s(v) { v »%» 26 »+» 65 -> map{.chr}.join }   func blacken (red, key) { v2s(s2v(red) »+« s2v(key)) } func redden (blk, key) { v2s(s2v(blk) »-« s2v(key)) }   var red = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!" var key = "Vigene...
http://rosettacode.org/wiki/Vector_products
Vector products
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numbers,   (X, Y, Z)   would repr...
#Euphoria
Euphoria
constant X = 1, Y = 2, Z = 3   function dot_product(sequence a, sequence b) return a[X]*b[X] + a[Y]*b[Y] + a[Z]*b[Z] end function   function cross_product(sequence a, sequence b) return { a[Y]*b[Z] - a[Z]*b[Y], a[Z]*b[X] - a[X]*b[Z], a[X]*b[Y] - a[Y]*b[X] } end function   function scal...
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number
Validate International Securities Identification Number
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct format,   and   the embedded c...
#langur
langur
val .luhntest = f(.s) { val .t = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9] val .numbers = s2n .s val .oddeven = len(.numbers) rem 2   for[=0] .i of .numbers { _for += if(.i rem 2 == .oddeven: .numbers[.i]; .t[.numbers[.i]+1]) } div 10 }   val .isintest = f(.s) { matching(re/^[A-Z][A-Z][0-9A-Z]{9}[0...
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number
Validate International Securities Identification Number
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct format,   and   the embedded c...
#Lua
Lua
function luhn (n) local revStr, s1, s2, digit, mod = n:reverse(), 0, 0 for pos = 1, #revStr do digit = tonumber(revStr:sub(pos, pos)) if pos % 2 == 1 then s1 = s1 + digit else digit = digit * 2 if digit > 9 then mod = digit % 10 ...
http://rosettacode.org/wiki/Van_der_Corput_sequence
Van der Corput sequence
When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 {\displaystyle 2^{1}} ; and so o...
#Icon_and_Unicon
Icon and Unicon
procedure main(A) base := integer(get(A)) | 2 every writes(round(vdc(0 to 9,base),10)," ") write() end   procedure vdc(n, base) e := 1.0 x := 0.0 while x +:= 1(((0 < n) % base) / (e *:= base), n /:= base) return x end   procedure round(n,d) places := 10 ^ d return real(integer(n*plac...
http://rosettacode.org/wiki/Van_der_Corput_sequence
Van der Corput sequence
When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 {\displaystyle 2^{1}} ; and so o...
#J
J
vdc=: ([ %~ %@[ #. #.inv)"0 _
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   Th...
#Crystal
Crystal
require "uri"   puts URI.decode "http%3A%2F%2Ffoo%20bar%2F" puts URI.decode "google.com/search?q=%60Abdu%27l-Bah%C3%A1"
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   Th...
#D
D
import std.stdio, std.uri;   void main() { writeln(decodeComponent("http%3A%2F%2Ffoo%20bar%2F")); }
http://rosettacode.org/wiki/UPC
UPC
Goal Convert UPC bar codes to decimal. Specifically: The UPC standard is actually a collection of standards -- physical standards, data format standards, product reference standards... Here,   in this task,   we will focus on some of the data format standards,   with an imaginary physical+electrical implementati...
#ALGOL_68
ALGOL 68
BEGIN # number of digits encoded by UPC # INT upc digits = 12; # MODE to hold UPC bar code parse results # MODE UPC = STRUCT( BOOL valid # TRUE if the UPC was valid, # # ...
http://rosettacode.org/wiki/Update_a_configuration_file
Update a configuration file
We have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines begininning with a hash or a semicolon are ignored by the application # program. Blank lines are also ignored by the application program. # The first word on each non comment line is the configurati...
#Fortran
Fortran
PROGRAM TEST !Define some data aggregates, then write and read them. CHARACTER*28 FAVOURITEFRUIT LOGICAL NEEDSPEELING LOGICAL SEEDSREMOVED INTEGER NUMBEROFBANANAS NAMELIST /FRUIT/ FAVOURITEFRUIT,NEEDSPEELING,SEEDSREMOVED, 1 NUMBEROFBANANAS INTEGER F !An I/O unit number. ...
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#Ceylon
Ceylon
shared void run() { print("enter any text here"); value text = process.readLine(); print(text); print("enter the number 75000 here"); if (is Integer number = Integer.parse(process.readLine() else "")) { print("``number == 75k then number else "close enough"``"); } else { print("That was not a number per se."...
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#Clojure
Clojure
(import '(java.util Scanner)) (def scan (Scanner. *in*)) (def s (.nextLine scan)) (def n (.nextInt scan))
http://rosettacode.org/wiki/User_input/Graphical
User input/Graphical
In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
#Frink
Frink
  s = input["Enter a string: "] i = parseInt[input["Enter an integer: "]]  
http://rosettacode.org/wiki/User_input/Graphical
User input/Graphical
In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
#Gambas
Gambas
hTextBox As TextBox hValueBox As ValueBox hLabel As Label   Public Sub Form_Open()   With Me .Height = 100 .Width = 300 .padding = 5 .Arrangement = Arrange.Vertical .Title = "User input/Graphical" End With   hTextBox = New TextBox(Me) As "TextBox1" hTextBox.Expand = True   hValueBox = New ValueBox(Me) As "Val...
http://rosettacode.org/wiki/UTF-8_encode_and_decode
UTF-8 encode and decode
As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets. The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the...
#Forth
Forth
: showbytes ( c-addr u -- ) over + swap ?do i c@ 3 .r loop ;   : test {: xc -- :} xc xemit xc 6 .r xc pad xc!+ pad tuck - ( c-addr u ) 2dup showbytes drop xc@+ xc <> abort" test failed" drop cr ;   hex $41 test $f6 test $416 test $20ac test $1d11e test \ can also be written as \ 'A' test 'ö' test 'Ж' test ...
http://rosettacode.org/wiki/UTF-8_encode_and_decode
UTF-8 encode and decode
As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets. The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the...
#Go
Go
package main   import ( "bytes" "encoding/hex" "fmt" "log" "strings" )   var testCases = []struct { rune string }{ {'A', "41"}, {'ö', "C3 B6"}, {'Ж', "D0 96"}, {'€', "E2 82 AC"}, {'𝄞', "F0 9D 84 9E"}, }   func main() { for _, tc := range testCases { // derive...
http://rosettacode.org/wiki/Use_another_language_to_call_a_function
Use another language to call a function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (i...
#Pascal
Pascal
without js -- (peek/poke, call_back) constant Here_am_I = "Here am I" function Query(atom pData, pLength) integer len = peekNS(pLength,machine_word(),0) if poke_string(pData,len,Here_am_I) then return 0 end if pokeN(pLength,length(Here_am_I)+1,machine_word()) return 1 end function constant Q...
http://rosettacode.org/wiki/Use_another_language_to_call_a_function
Use another language to call a function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (i...
#Phix
Phix
without js -- (peek/poke, call_back) constant Here_am_I = "Here am I" function Query(atom pData, pLength) integer len = peekNS(pLength,machine_word(),0) if poke_string(pData,len,Here_am_I) then return 0 end if pokeN(pLength,length(Here_am_I)+1,machine_word()) return 1 end function constant Q...
http://rosettacode.org/wiki/URL_parser
URL parser
URLs are strings with a simple syntax: scheme://[username:password@]domain[:port]/path?query_string#fragment_id Task Parse a well-formed URL to retrieve the relevant information:   scheme, domain, path, ... Note:   this task has nothing to do with URL encoding or URL decoding. According to the standards, t...
#M2000_Interpreter
M2000 Interpreter
  Module checkit { any=lambda (z$)->{=lambda z$ (a$)->instr(z$,a$)>0} one=lambda (z$)->{=lambda z$ (a$)->z$=a$} number$="0123456789"   series=Lambda -> { func=Array([]) =lambda func (&line$, &res$)->{ if line$="" then exit ...
http://rosettacode.org/wiki/URL_parser
URL parser
URLs are strings with a simple syntax: scheme://[username:password@]domain[:port]/path?query_string#fragment_id Task Parse a well-formed URL to retrieve the relevant information:   scheme, domain, path, ... Note:   this task has nothing to do with URL encoding or URL decoding. According to the standards, t...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
URLParse["foo://example.com:8042/over/there?name=ferret#nose"]
http://rosettacode.org/wiki/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. Fo...
#Free_Pascal
Free Pascal
function urlEncode(data: string): AnsiString; var ch: AnsiChar; begin Result := ''; for ch in data do begin if ((Ord(ch) < 65) or (Ord(ch) > 90)) and ((Ord(ch) < 97) or (Ord(ch) > 122)) then begin Result := Result + '%' + IntToHex(Ord(ch), 2); end else Result := Result + ch; end; end;
http://rosettacode.org/wiki/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. Fo...
#FreeBASIC
FreeBASIC
  Dim Shared As String lookUp(256) For cadena As Integer = 0 To 256 lookUp(cadena) = "%" + Hex(cadena) Next cadena   Function string2url(cadena As String) As String Dim As String cadTemp, cadDevu For j As Integer = 1 To Len(cadena) cadTemp = Mid(cadena, j, 1) If Instr( "0123456789ABCDEFGHIJK...
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#E
E
def x := 1 x + x # returns 2
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#EasyLang
EasyLang
# it is statically typed # # global number variable n = 99 print n # global array of numbers a[] = [ 2.1 3.14 3 ] # func f . . # i is local, because it is first used in the function for i range len a[] print a[i] . . call f # # string domain$ = "easylang.online" print domain$ # # array of strings fruits...
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using ...
#JavaScript
JavaScript
(() => { 'use strict';   // vanEck :: Int -> [Int] const vanEck = n => reverse( churchNumeral(n)( xs => 0 < xs.length ? cons( maybe( 0, succ, elemIndex(xs[0], xs.slice(1)) ), ...
http://rosettacode.org/wiki/Vampire_number
Vampire number
A vampire number is a natural decimal number with an even number of digits,   that can be factored into two integers. These two factors are called the   fangs,   and must have the following properties:   they each contain half the number of the decimal digits of the original number   together they consist of exactl...
#PureBasic
PureBasic
EnableExplicit DisableDebugger   Macro CheckVamp(CheckNum) c=0 : i=CheckNum : Print(~"\nCheck number: "+Str(i)+~"\n") Gosub VampireLoop : If c=0 : Print(Str(i)+" is not vampiric.") : EndIf : PrintN("") EndMacro   Procedure.i Factor(number.i,counter.i) If number>0 And number>=counter*counter And number%counter=0 ...
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function...
#Maxima
Maxima
show([L]) := block([n], n: length(L), for i from 1 thru n do disp(L[i]))$   show(1, 2, 3, 4);   apply(show, [1, 2, 3, 4]);   /* Actually, the built-in function "disp" is already what we want */ disp(1, 2, 3, 4);   apply(disp, [1, 2, 3, 4]);
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function...
#Metafont
Metafont
def print_arg(text t) = for x = t: if unknown x: message "unknown value" elseif numeric x: message decimal x elseif string x: message x elseif path x: message "a path" elseif pair x: message decimal (xpart(x)) & ", " & decimal (ypart(x)) elseif boolean x: if x: message "true!" else: message "false!" fi el...
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to...
#Swift
Swift
import Foundation #if canImport(Numerics) import Numerics #endif   struct Vector<T: Numeric> { var x: T var y: T   func prettyPrinted(precision: Int = 4) -> String where T: CVarArg & FloatingPoint { return String(format: "[%.\(precision)f, %.\(precision)f]", x, y) }   static func +(lhs: Vector, rhs: Vecto...
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to...
#Tcl
Tcl
namespace path ::tcl::mathop proc vec {op a b} { if {[llength $a] == 1 && [llength $b] == 1} { $op $a $b } elseif {[llength $a]==1} { lmap i $b {vec $op $a $i} } elseif {[llength $b]==1} { lmap i $a {vec $op $i $b} } elseif {[llength $a] == [llength $b]} { lmap i $a j $b ...
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher
Vigenère cipher
Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) Related tasks   Caesar ...
#Smalltalk
Smalltalk
  prep := [:s | s select:[:ch | ch isLetter] thenCollect:[:ch | ch asUppercase]]. encrypt := [:s :cypher | (prep value:s) keysAndValuesCollect:[:i :ch | ch rot:((cypher at:((i-1)\\key size+1))-$A) ]]. decrypt := [:s :cypher | (prep value:s) keysAndValuesCollect:[:i :ch | ch rot:26-((cypher at:((i-1)\\key size+1))-$A) ]...
http://rosettacode.org/wiki/Vector_products
Vector products
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numbers,   (X, Y, Z)   would repr...
#F.23
F#
let dot (ax, ay, az) (bx, by, bz) = ax * bx + ay * by + az * bz   let cross (ax, ay, az) (bx, by, bz) = (ay*bz - az*by, az*bx - ax*bz, ax*by - ay*bx)   let scalTrip a b c = dot a (cross b c)   let vecTrip a b c = cross a (cross b c)   [<EntryPoint>] let main _ = let a = (3.0, 4.0, 5.0) let b = ...
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number
Validate International Securities Identification Number
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct format,   and   the embedded c...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[LuhnQ, VakudISINQ] LuhnQ[n_Integer] := Block[{digits = Reverse@IntegerDigits@n}, Mod[Total[{digits[[;; ;; 2]], IntegerDigits[2 #] & /@ digits[[2 ;; ;; 2]]}, -1], 10] == 0] VakudISINQ[sin_String] := Module[{s = ToUpperCase[sin]}, If[StringMatchQ[s, LetterCharacter ~~ LetterCharacter ~~ Repeated[Dig...
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number
Validate International Securities Identification Number
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct format,   and   the embedded c...
#Nim
Nim
import strformat   const DigitRange = '0'..'9' UpperCaseRange = 'A'..'Z'   type ISINError = object of ValueError     proc luhn(s: string): bool = const m = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9] var sum = 0 var odd = true for i in countdown(s.high, 0): let digit = ord(s[i]) - ord('0') sum += (if odd: digit ...
http://rosettacode.org/wiki/Van_der_Corput_sequence
Van der Corput sequence
When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 {\displaystyle 2^{1}} ; and so o...
#Java
Java
public class VanDerCorput{ public static double vdc(int n){ double vdc = 0; int denom = 1; while(n != 0){ vdc += n % 2.0 / (denom *= 2); n /= 2; } return vdc; }   public static void main(String[] args){ for(int i = 0; i <= 10; i++){ System.out.println(vdc(i)); } } }
http://rosettacode.org/wiki/Van_der_Corput_sequence
Van der Corput sequence
When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 {\displaystyle 2^{1}} ; and so o...
#jq
jq
# vdc(base) converts an input decimal integer to a decimal number based on the van der # Corput sequence using base 'base', e.g. (4 | vdc(2)) is 0.125. # def vdc(base):   # The helper function converts a stream of residuals to a decimal, # e.g. if base is 2, then decimalize( (0,0,1) ) yields 0.125 def decimalize(...
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   Th...
#Delphi
Delphi
program URLEncoding;   {$APPTYPE CONSOLE}   uses IdURI;   begin Writeln(TIdURI.URLDecode('http%3A%2F%2Ffoo%20bar%2F')); end.
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   Th...
#Elixir
Elixir
IO.inspect URI.decode("http%3A%2F%2Ffoo%20bar%2F") IO.inspect URI.decode("google.com/search?q=%60Abdu%27l-Bah%C3%A1")
http://rosettacode.org/wiki/UPC
UPC
Goal Convert UPC bar codes to decimal. Specifically: The UPC standard is actually a collection of standards -- physical standards, data format standards, product reference standards... Here,   in this task,   we will focus on some of the data format standards,   with an imaginary physical+electrical implementati...
#AutoHotkey
AutoHotkey
UPC2Dec(code){ lBits :={" ## #":0," ## #":1," # ##":2," #### #":3," # ##":4," ## #":5," # ####":6," ### ##":7," ## ###":8," # ##":9} xlBits:={"# ## ":0,"# ## ":1,"## # ":2,"# #### ":3,"## # ":4,"# ## ":5,"#### # ":6,"## ### ":7,"### ## ":8,"## # ":9} rBits :={"### # ":0,"## ## ":1,...
http://rosettacode.org/wiki/Update_a_configuration_file
Update a configuration file
We have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines begininning with a hash or a semicolon are ignored by the application # program. Blank lines are also ignored by the application program. # The first word on each non comment line is the configurati...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Type ConfigData favouriteFruit As String needsPeeling As Boolean seedsRemoved As Boolean numberOfBananas As UInteger numberOfStrawberries As UInteger End Type   Sub updateConfigData(fileName As String, cData As ConfigData) Dim fileNum As Integer = FreeFile Open fileName For Input As #f...
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. Get-Input.   DATA DIVISION. WORKING-STORAGE SECTION. 01 Input-String PIC X(30). 01 Input-Int PIC 9(5).   PROCEDURE DIVISION. DISPLAY "Enter a string:" ACCEPT Input-String   DISPLAY "Enter a number:" AC...
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#Common_Lisp
Common Lisp
(format t "Enter some text: ") (let ((s (read-line))) (format t "You entered ~s~%" s))   (format t "Enter a number: ") (let ((n (read))) (if (numberp n) (format t "You entered ~d.~%" n) (format t "That was not a number.")))
http://rosettacode.org/wiki/User_input/Graphical
User input/Graphical
In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
#Go
Go
package main   import ( "github.com/gotk3/gotk3/gtk" "log" "math/rand" "strconv" "time" )   func validateInput(window *gtk.Window, str1, str2 string) bool { n, err := strconv.ParseFloat(str2, 64) if len(str1) == 0 || err != nil || n != 75000 { dialog := gtk.MessageDialogNew( ...
http://rosettacode.org/wiki/UTF-8_encode_and_decode
UTF-8 encode and decode
As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets. The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the...
#Groovy
Groovy
import java.nio.charset.StandardCharsets   class UTF8EncodeDecode { static byte[] utf8encode(int codePoint) { char[] characters = [codePoint] new String(characters, 0, 1).getBytes StandardCharsets.UTF_8 }   static int utf8decode(byte[] bytes) { new String(bytes, StandardCharsets.UTF_...
http://rosettacode.org/wiki/Use_another_language_to_call_a_function
Use another language to call a function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (i...
#PicoLisp
PicoLisp
(let (Str "Here am I" Len (format (opt))) # Get length from command line (unless (>= (size Str) Len) # Check buffer size (prinl Str) ) ) # Return string if OK
http://rosettacode.org/wiki/Use_another_language_to_call_a_function
Use another language to call a function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (i...
#Python
Python
  # store this in file rc_embed.py # store this in file rc_embed.py def query(buffer_length): message = b'Here am I' L = len(message) return message[0:L*(L <= buffer_length)]  
http://rosettacode.org/wiki/URL_parser
URL parser
URLs are strings with a simple syntax: scheme://[username:password@]domain[:port]/path?query_string#fragment_id Task Parse a well-formed URL to retrieve the relevant information:   scheme, domain, path, ... Note:   this task has nothing to do with URL encoding or URL decoding. According to the standards, t...
#Nim
Nim
import uri, strformat   proc printUri(url: string) = echo url let res = parseUri(url) if res.scheme != "": echo &"\t Scheme: {res.scheme}" if res.hostname != "": echo &"\tHostname: {res.hostname}" if res.username != "": echo &"\tUsername: {res.username}" if res.password != "": echo &"\tPass...
http://rosettacode.org/wiki/URL_parser
URL parser
URLs are strings with a simple syntax: scheme://[username:password@]domain[:port]/path?query_string#fragment_id Task Parse a well-formed URL to retrieve the relevant information:   scheme, domain, path, ... Note:   this task has nothing to do with URL encoding or URL decoding. According to the standards, t...
#Objeck
Objeck
use Web.HTTP;   class Test { function : Main(args : String[]) ~ Nil { urls := [ "foo://example.com:8042/over/there?name=ferret#nose", "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", ...
http://rosettacode.org/wiki/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. Fo...
#Frink
Frink
println[URLEncode["http://foo bar/"]]
http://rosettacode.org/wiki/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. Fo...
#Go
Go
package main   import ( "fmt" "net/url" )   func main() { fmt.Println(url.QueryEscape("http://foo bar/")) }
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#Eiffel
Eiffel
  class APPLICATION inherit ARGUMENTS create make   feature {NONE} -- Initialization   make -- Run application. local i: INTEGER s: STRING do i := 100 s := "Some string" create a.make_empty end   feature {NONE} -- Class Features   a: ARRAY[INTEGER]  
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#Ela
Ela
x = 42   sum x y = x + y
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using ...
#jq
jq
# Input: an array # If the rightmost element, .[-1], does not occur elsewhere, return 0; # otherwise return the "depth" of its rightmost occurrence in .[0:-2] def depth: .[-1] as $x | length as $length | first(range($length-2; -1; -1) as $i | select(.[$i] == $x) | $length - 1 - $i) // 0 ;   # Gener...
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using ...
#Julia
Julia
function vanecksequence(N, startval=0) ret = zeros(Int, N) ret[1] = startval for i in 1:N-1 lastseen = findlast(x -> x == ret[i], ret[1:i-1]) if lastseen != nothing ret[i + 1] = i - lastseen end end ret end   println(vanecksequence(10)) println(vanecksequence(1000...
http://rosettacode.org/wiki/Vampire_number
Vampire number
A vampire number is a natural decimal number with an even number of digits,   that can be factored into two integers. These two factors are called the   fangs,   and must have the following properties:   they each contain half the number of the decimal digits of the original number   together they consist of exactl...
#Python
Python
from __future__ import division   import math from operator import mul from itertools import product from functools import reduce     def fac(n): '''\ return the prime factors for n >>> fac(600) [5, 5, 3, 2, 2, 2] >>> fac(1000) [5, 5, 5, 2, 2, 2] >>> ''' step = lambda x: 1 + x*4 - ...
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function...
#Modula-3
Modula-3
MODULE Varargs EXPORTS Main;   IMPORT IO;   VAR strings := ARRAY [1..5] OF TEXT {"foo", "bar", "baz", "quux", "zeepf"};   PROCEDURE Variable(VAR arr: ARRAY OF TEXT) = BEGIN FOR i := FIRST(arr) TO LAST(arr) DO IO.Put(arr[i] & "\n"); END; END Variable;   BEGIN Variable(strings); END Varargs.
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function...
#Nemerle
Nemerle
using System; using System.Console;   module Variadic { PrintAll (params args : array[object]) : void { foreach (arg in args) WriteLine(arg); }   Main() : void { PrintAll("test", "rosetta code", 123, 5.6, DateTime.Now); } }
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to...
#VBA
VBA
Type vector x As Double y As Double End Type Type vector2 phi As Double r As Double End Type Private Function vector_addition(u As vector, v As vector) As vector vector_addition.x = u.x + v.x vector_addition.y = u.y + v.y End Function Private Function vector_subtraction(u As vector, v As vector)...
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to...
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Class Vector Public store As Double()   Public Sub New(init As IEnumerable(Of Double)) store = init.ToArray() End Sub   Public Sub New(x As Double, y As Double) store = {x, y} End Sub   Public Overloads Shared Operator +(v1 As ...
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher
Vigenère cipher
Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) Related tasks   Caesar ...
#Swift
Swift
public func convertToUnicodeScalars( str: String, minChar: UInt32, maxChar: UInt32 ) -> [UInt32] { var scalars = [UInt32]()   for scalar in str.unicodeScalars { let val = scalar.value   guard val >= minChar && val <= maxChar else { continue }   scalars.append(val) }   return scalars ...
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher
Vigenère cipher
Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) Related tasks   Caesar ...
#Tcl
Tcl
package require Tcl 8.6   oo::class create Vigenere { variable key constructor {protoKey} { foreach c [split $protoKey ""] { if {[regexp {[A-Za-z]} $c]} { lappend key [scan [string toupper $c] %c] } } }   method encrypt {text} { set out "" set j 0 foreach c [split $text ""] { if {[...