code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
import Graphics.UI.Gtk
import Control.Monad
main = do
initGUI
window <- windowNew
set window [windowTitle:= "Graphical user input", containerBorderWidth:= 10]
vb <- vBoxNew False 0
containerAdd window vb
hb1 <- hBoxNew False 0
boxPackStart vb hb1 PackNatural 0
hb2 <- hBoxNew False 0
boxPackStart vb hb2 PackNatural 0
lab1 <- labelNew (Just "Enter number 75000")
boxPackStart hb1 lab1 PackNatural 0
nrfield <- entryNew
entrySetText nrfield "75000"
boxPackStart hb1 nrfield PackNatural 5
strfield <- entryNew
boxPackEnd hb2 strfield PackNatural 5
lab2 <- labelNew (Just "Enter a text")
boxPackEnd hb2 lab2 PackNatural 0
accbox <- hBoxNew False 0
boxPackStart vb accbox PackNatural 5
im <- imageNewFromStock stockApply IconSizeButton
acceptButton <- buttonNewWithLabel "Accept"
buttonSetImage acceptButton im
boxPackStart accbox acceptButton PackRepel 0
txtstack <- statusbarNew
boxPackStart vb txtstack PackNatural 0
id <- statusbarGetContextId txtstack "Line"
widgetShowAll window
onEntryActivate nrfield (showStat nrfield txtstack id)
onEntryActivate strfield (showStat strfield txtstack id)
onPressed acceptButton $ do
g <- entryGetText nrfield
if g=="75000" then
widgetDestroy window
else do
msgid <- statusbarPush txtstack id "You didn't enter 75000. Try again"
return ()
onDestroy window mainQuit
mainGUI
showStat :: Entry -> Statusbar -> ContextId -> IO ()
showStat fld stk id = do
txt <- entryGetText fld
let mesg = "You entered \"" ++ txt ++ "\""
msgid <- statusbarPush stk id mesg
return () | 82User input/Graphical
| 8haskell
| 8xr0z |
import java.nio.charset.StandardCharsets;
import java.util.Formatter;
public class UTF8EncodeDecode {
public static byte[] utf8encode(int codepoint) {
return new String(new int[]{codepoint}, 0, 1).getBytes(StandardCharsets.UTF_8);
}
public static int utf8decode(byte[] bytes) {
return new String(bytes, StandardCharsets.UTF_8).codePointAt(0);
}
public static void main(String[] args) {
System.out.printf("%-7s%-43s%7s\t%s\t%7s%n",
"Char", "Name", "Unicode", "UTF-8 encoded", "Decoded");
for (int codepoint : new int[]{0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E}) {
byte[] encoded = utf8encode(codepoint);
Formatter formatter = new Formatter();
for (byte b : encoded) {
formatter.format("%02X ", b);
}
String encodedHex = formatter.toString();
int decoded = utf8decode(encoded);
System.out.printf("%-7c%-43s U+%04X\t%-12s\tU+%04X%n",
codepoint, Character.getName(codepoint), codepoint, encodedHex, decoded);
}
}
} | 79UTF-8 encode and decode
| 9java
| 938mu |
require 'fiddle'
c_var = Fiddle.dlopen(nil)['QueryPointer']
int = Fiddle::TYPE_INT
voidp = Fiddle::TYPE_VOIDP
sz_voidp = Fiddle::SIZEOF_VOIDP
Query = Fiddle::Closure::BlockCaller
.new(int, [voidp, voidp]) do |datap, lengthp|
message =
length = lengthp[0, sz_voidp].unpack('J').first
if length < message.bytesize
0
else
length = message.bytesize
datap[0, length] = message
lengthp[0, sz_voidp] = [length].pack('J')
1
end
end
Fiddle::Pointer.new(c_var)[0, sz_voidp] = [Query.to_i].pack('J') | 75Use another language to call a function
| 14ruby
| rucgs |
null | 75Use another language to call a function
| 15rust
| 75lrc |
null | 74Van Eck sequence
| 1lua
| 0w1sd |
const
utf8encode=
n=>
(m=>
m<0x80
?Uint8Array.from(
[ m>>0&0x7f|0x00])
:m<0x800
?Uint8Array.from(
[ m>>6&0x1f|0xc0,m>>0&0x3f|0x80])
:m<0x10000
?Uint8Array.from(
[ m>>12&0x0f|0xe0,m>>6&0x3f|0x80,m>>0&0x3f|0x80])
:m<0x110000
?Uint8Array.from(
[ m>>18&0x07|0xf0,m>>12&0x3f|0x80,m>>6&0x3f|0x80,m>>0&0x3f|0x80])
:(()=>{throw'Invalid Unicode Code Point!'})())
( typeof n==='string'
?n.codePointAt(0)
:n&0x1fffff),
utf8decode=
([m,n,o,p])=>
m<0x80
?( m&0x7f)<<0
:0xc1<m&&m<0xe0&&n===(n&0xbf)
?( m&0x1f)<<6|( n&0x3f)<<0
:( m===0xe0&&0x9f<n&&n<0xc0
||0xe0<m&&m<0xed&&0x7f<n&&n<0xc0
||m===0xed&&0x7f<n&&n<0xa0
||0xed<m&&m<0xf0&&0x7f<n&&n<0xc0)
&&o===o&0xbf
?( m&0x0f)<<12|( n&0x3f)<<6|( o&0x3f)<<0
:( m===0xf0&&0x8f<n&&n<0xc0
||m===0xf4&&0x7f<n&&n<0x90
||0xf0<m&&m<0xf4&&0x7f<n&&n<0xc0)
&&o===o&0xbf&&p===p&0xbf
?( m&0x07)<<18|( n&0x3f)<<12|( o&0x3f)<<6|( p&0x3f)<<0
:(()=>{throw'Invalid UTF-8 encoding!'})() | 79UTF-8 encode and decode
| 10javascript
| ucfvb |
object Query {
def call(data: Array[Byte], length: Array[Int]): Boolean = {
val message = "Here am I"
val mb = message.getBytes("utf-8")
if (length(0) >= mb.length) {
length(0) = mb.length
System.arraycopy(mb, 0, data, 0, mb.length)
true
} else false
}
} | 75Use another language to call a function
| 16scala
| kruhk |
<?php
$urls = array(
'foo:
'urn:example:animal:ferret:nose',
'jdbc:mysql:
'ftp:
'http:
'ldap:
'mailto:[email protected]',
'news:comp.infosystems.www.servers.unix',
'tel:+1-816-555-1212',
'telnet:
'urn:oasis:names:specification:docbook:dtd:xml:4.1.2',
);
foreach ($urls AS $url) {
$p = parse_url($url);
echo $url, PHP_EOL;
print_r($p);
echo PHP_EOL;
} | 77URL parser
| 12php
| x17w5 |
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class Main
{
public static void main(String[] args) throws UnsupportedEncodingException
{
String normal = "http: | 78URL encoding
| 9java
| d8an9 |
def factor_pairs n
first = n / (10 ** (n.to_s.size / 2) - 1)
(first .. n ** 0.5).map { |i| [i, n / i] if n % i == 0 }.compact
end
def vampire_factors n
return [] if n.to_s.size.odd?
half = n.to_s.size / 2
factor_pairs(n).select do |a, b|
a.to_s.size == half && b.to_s.size == half &&
[a, b].count {|x| x%10 == 0}!= 2 &&
.chars.sort == n.to_s.chars.sort
end
end
i = vamps = 0
until vamps == 25
vf = vampire_factors(i += 1)
unless vf.empty?
puts
vamps += 1
end
end
[16758243290880, 24959017348650, 14593825548650].each do |n|
if (vf = vampire_factors n).empty?
puts
else
puts
end
end | 70Vampire number
| 14ruby
| c6y9k |
package main
import (
"fmt"
"log"
"net/url"
)
func main() {
for _, escaped := range []string{
"http%3A%2F%2Ffoo%20bar%2F",
"google.com/search?q=%60Abdu%27l-Bah%C3%A1",
} {
u, err := url.QueryUnescape(escaped)
if err != nil {
log.Println(err)
continue
}
fmt.Println(u)
}
} | 80URL decoding
| 0go
| j4y7d |
import java.io.*;
import java.util.*;
import java.util.regex.*;
public class UpdateConfig {
public static void main(String[] args) {
if (args[0] == null) {
System.out.println("filename required");
} else if (readConfig(args[0])) {
enableOption("seedsremoved");
disableOption("needspeeling");
setOption("numberofbananas", "1024");
addOption("numberofstrawberries", "62000");
store();
}
}
private enum EntryType {
EMPTY, ENABLED, DISABLED, COMMENT
}
private static class Entry {
EntryType type;
String name, value;
Entry(EntryType t, String n, String v) {
type = t;
name = n;
value = v;
}
}
private static Map<String, Entry> entries = new LinkedHashMap<>();
private static String path;
private static boolean readConfig(String p) {
path = p;
File f = new File(path);
if (!f.exists() || f.isDirectory())
return false;
String regexString = "^(;*)\\s*([A-Za-z0-9]+)\\s*([A-Za-z0-9]*)";
Pattern regex = Pattern.compile(regexString);
try (Scanner sc = new Scanner(new FileReader(f))){
int emptyLines = 0;
String line;
while (sc.hasNext()) {
line = sc.nextLine().trim();
if (line.isEmpty()) {
addOption("" + emptyLines++, null, EntryType.EMPTY);
} else if (line.charAt(0) == '#') {
entries.put(line, new Entry(EntryType.COMMENT, line, null));
} else {
line = line.replaceAll("[^a-zA-Z0-9\\x20;]", "");
Matcher m = regex.matcher(line);
if (m.find() && !m.group(2).isEmpty()) {
EntryType t = EntryType.ENABLED;
if (!m.group(1).isEmpty())
t = EntryType.DISABLED;
addOption(m.group(2), m.group(3), t);
}
}
}
} catch (IOException e) {
System.out.println(e);
}
return true;
}
private static void addOption(String name, String value) {
addOption(name, value, EntryType.ENABLED);
}
private static void addOption(String name, String value, EntryType t) {
name = name.toUpperCase();
entries.put(name, new Entry(t, name, value));
}
private static void enableOption(String name) {
Entry e = entries.get(name.toUpperCase());
if (e != null)
e.type = EntryType.ENABLED;
}
private static void disableOption(String name) {
Entry e = entries.get(name.toUpperCase());
if (e != null)
e.type = EntryType.DISABLED;
}
private static void setOption(String name, String value) {
Entry e = entries.get(name.toUpperCase());
if (e != null)
e.value = value;
}
private static void store() {
try (PrintWriter pw = new PrintWriter(path)) {
for (Entry e : entries.values()) {
switch (e.type) {
case EMPTY:
pw.println();
break;
case ENABLED:
pw.format("%s%s%n", e.name, e.value);
break;
case DISABLED:
pw.format(";%s%s%n", e.name, e.value);
break;
case COMMENT:
pw.println(e.name);
break;
default:
break;
}
}
if (pw.checkError()) {
throw new IOException("writing to file failed");
}
} catch (IOException e) {
System.out.println(e);
}
}
} | 81Update a configuration file
| 9java
| krmhm |
var normal = 'http: | 78URL encoding
| 10javascript
| 6fs38 |
use std::cmp::{max, min};
static TENS: [u64; 20] = [
1,
10,
100,
1000,
10000,
100000,
1000000,
10000000,
100000000,
1000000000,
10000000000,
100000000000,
1000000000000,
10000000000000,
100000000000000,
1000000000000000,
10000000000000000,
100000000000000000,
1000000000000000000,
10000000000000000000,
]; | 70Vampire number
| 15rust
| lymcc |
import Stream._
import math._
import scala.collection.mutable.ListBuffer
object VampireNumbers extends App {
val elapsed: (=> Unit) => Long = f => {val s = System.currentTimeMillis; f; (System.currentTimeMillis - s)/1000}
val sexp = from(1, 2) | 70Vampire number
| 16scala
| uclv8 |
sub print_all {
foreach (@_) {
print "$_\n";
}
} | 67Variadic function
| 2perl
| i0no3 |
def check_isin(a):
if len(a) != 12 or not all(c.isalpha() for c in a[:2]) or not all(c.isalnum() for c in a[2:]):
return False
s = .join(str(int(c, 36)) for c in a)
return 0 == (sum(sum(divmod(2 * (ord(c) - 48), 10)) for c in s[-2::-2]) +
sum(ord(c) - 48 for c in s[::-2]))% 10
def check_isin_alt(a):
if len(a) != 12:
return False
s = []
for i, c in enumerate(a):
if c.isdigit():
if i < 2:
return False
s.append(ord(c) - 48)
elif c.isupper():
if i == 11:
return False
s += divmod(ord(c) - 55, 10)
else:
return False
v = sum(s[::-2])
for k in s[-2::-2]:
k = 2 * k
v += k - 9 if k > 9 else k
return v% 10 == 0
[check_isin(s) for s in [, , , ,
, , ]] | 71Validate International Securities Identification Number
| 3python
| gvv4h |
assert URLDecoder.decode('http%3A%2F%2Ffoo%20bar%2F') == 'http: | 80URL decoding
| 7groovy
| 5lfuv |
import qualified Data.Char as Char
urlDecode :: String -> Maybe String
urlDecode [] = Just []
urlDecode ('%':xs) =
case xs of
(a:b:xss) ->
urlDecode xss
>>= return . ((Char.chr . read $ "0x" ++ [a,b]):)
_ -> Nothing
urlDecode ('+':xs) = urlDecode xs >>= return . (' ':)
urlDecode (x:xs) = urlDecode xs >>= return . (x:)
main :: IO ()
main = putStrLn . maybe "Bad decode" id $ urlDecode "http%3A%2F%2Ffoo%20bar%2F" | 80URL decoding
| 8haskell
| oqh8p |
null | 81Update a configuration file
| 11kotlin
| gvt4d |
import javax.swing.*;
public class GetInputSwing {
public static void main(String[] args) throws Exception {
int number = Integer.parseInt(
JOptionPane.showInputDialog ("Enter an Integer"));
String string = JOptionPane.showInputDialog ("Enter a String");
}
} | 82User input/Graphical
| 9java
| eb2a5 |
var str = prompt("Enter a string");
var value = 0;
while (value != 75000) {
value = parseInt( prompt("Enter the number 75000") );
} | 82User input/Graphical
| 10javascript
| 0wgsz |
null | 79UTF-8 encode and decode
| 11kotlin
| znwts |
import urllib.parse as up
url = up.urlparse('http:
print('url.scheme = ', url.scheme)
print('url.netloc = ', url.netloc)
print('url.hostname = ', url.hostname)
print('url.port = ', url.port)
print('url.path = ', url.path)
print('url.params = ', url.params)
print('url.query = ', url.query)
print('url.fragment = ', url.fragment)
print('url.username = ', url.username)
print('url.password = ', url.password) | 77URL parser
| 3python
| lydcv |
null | 78URL encoding
| 11kotlin
| 0whsf |
use strict;
use warnings;
use feature 'say';
sub van_eck {
my($init,$max) = @_;
my(%v,$k);
my @V = my $i = $init;
for (1..$max) {
$k++;
my $t = $v{$i} ? $k - $v{$i} : 0;
$v{$i} = $k;
push @V, $i = $t;
}
@V;
}
for (
['A181391', 0],
['A171911', 1],
['A171912', 2],
['A171913', 3],
['A171914', 4],
['A171915', 5],
['A171916', 6],
['A171917', 7],
['A171918', 8],
) {
my($seq, $start) = @$_;
my @seq = van_eck($start,1000);
say <<~"END";
Van Eck sequence OEIS:$seq; with the first term: $start
First 10 terms: @{[@seq[0 .. 9]]}
Terms 991 through 1000: @{[@seq[990..999]]}
END
} | 74Van Eck sequence
| 2perl
| ucyvr |
<?php
function printAll() {
foreach (func_get_args() as $x)
echo ;
$numargs = func_num_args();
for ($i = 0; $i < $numargs; $i++)
echo func_get_arg($i), ;
}
printAll(4, 3, 5, 6, 4, 3);
printAll(4, 3, 5);
printAll(, , , );
?> | 67Variadic function
| 12php
| r57ge |
package main
import (
"fmt"
"regexp"
)
var bits = []string{
"0 0 0 1 1 0 1 ",
"0 0 1 1 0 0 1 ",
"0 0 1 0 0 1 1 ",
"0 1 1 1 1 0 1 ",
"0 1 0 0 0 1 1 ",
"0 1 1 0 0 0 1 ",
"0 1 0 1 1 1 1 ",
"0 1 1 1 0 1 1 ",
"0 1 1 0 1 1 1 ",
"0 0 0 1 0 1 1 ",
}
var (
lhs = make(map[string]int)
rhs = make(map[string]int)
)
var weights = []int{3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1}
const (
s = "# #"
m = " # # "
e = "# #"
d = "(?:#| ){7}"
)
func init() {
for i := 0; i <= 9; i++ {
lt := make([]byte, 7)
rt := make([]byte, 7)
for j := 0; j < 14; j += 2 {
if bits[i][j] == '1' {
lt[j/2] = '#'
rt[j/2] = ' '
} else {
lt[j/2] = ' '
rt[j/2] = '#'
}
}
lhs[string(lt)] = i
rhs[string(rt)] = i
}
}
func reverse(s string) string {
b := []byte(s)
for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
b[i], b[j] = b[j], b[i]
}
return string(b)
}
func main() {
barcodes := []string{
" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ",
" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ",
" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ",
" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ",
" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ",
" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ",
" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ",
" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ",
" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ",
" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ",
} | 84UPC
| 0go
| lyqcw |
null | 82User input/Graphical
| 11kotlin
| kryh3 |
library(urltools)
urls <- c("foo://example.com:8042/over/there?name=ferret
"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
"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two",
"mailto:[email protected]",
"news:comp.infosystems.www.servers.unix",
"tel:+1-816-555-1212",
"telnet://192.0.2.16:80/",
"urn:oasis:names:specification:docbook:dtd:xml:4.1.2",
"ssh://[email protected]",
"https://bob:[email protected]/place",
"http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64")
for (an_url in urls) {
parsed <- url_parse(an_url)
cat(an_url,"\n")
for (idx in 1:ncol(parsed)) {
if (!is.na(parsed[[idx]])) {
cat(colnames(parsed)[[idx]],"\t:",parsed[[idx]],"\n")
}
}
cat("\n")
} | 77URL parser
| 13r
| yt86h |
x := 3 | 76Variables
| 0go
| krvhz |
import Foundation
func vampire<T>(n: T) -> [(T, T)] where T: BinaryInteger, T.Stride: SignedInteger {
let strN = String(n).sorted()
let fangLength = strN.count / 2
let start = T(pow(10, Double(fangLength - 1)))
let end = T(Double(n).squareRoot())
var fangs = [(T, T)]()
for i in start...end where n% i == 0 {
let quot = n / i
guard i% 10!= 0 || quot% 10!= 0 else {
continue
}
if "\(i)\(quot)".sorted() == strN {
fangs.append((i, quot))
}
}
return fangs
}
var count = 0
var i = 1.0
while count < 25 {
let start = Int(pow(10, i))
let end = start * 10
for num in start...end {
let fangs = vampire(n: num)
guard!fangs.isEmpty else { continue }
count += 1
print("\(num) is a vampire number with fangs: \(fangs)")
guard count!= 25 else { break }
}
i += 2
}
for (vamp, fangs) in [16758243290880, 24959017348650, 14593825548650].lazy.map({ ($0, vampire(n: $0)) }) {
if fangs.isEmpty {
print("\(vamp) is not a vampire number")
} else {
print("\(vamp) is a vampire number with fangs: \(fangs)")
}
} | 70Vampire number
| 17swift
| 936mj |
sub vdc {
my @value = shift;
my $base = shift // 2;
use integer;
push @value, $value[-1] / $base while $value[-1] > 0;
my ($x, $sum) = (1, 0);
no integer;
$sum += ($_ % $base) / ($x *= $base) for @value;
return $sum;
}
for my $base ( 2 .. 5 ) {
print "base $base: ", join ' ', map { vdc($_, $base) } 0 .. 10;
print "\n";
} | 73Van der Corput sequence
| 2perl
| 0was4 |
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
public class Main
{
public static void main(String[] args) throws UnsupportedEncodingException
{
String encoded = "http%3A%2F%2Ffoo%20bar%2F";
String normal = URLDecoder.decode(encoded, "utf-8");
System.out.println(normal);
}
} | 80URL decoding
| 9java
| wp5ej |
decodeURIComponent("http%3A%2F%2Ffoo%20bar%2F") | 80URL decoding
| 10javascript
| 8xj0l |
use warnings;
use strict;
my $needspeeling = 0;
my $seedsremoved = 1;
my $numberofstrawberries = 62000;
my $numberofbananas = 1024;
my $favouritefruit = 'bananas';
my @out;
sub config {
my (@config) = <DATA>;
push @config, "NUMBEROFSTRAWBERRIES $numberofstrawberries\n"
unless grep { /^;*[ \t]*NUMBEROFSTRAWBERRIES\b/; } @config;
foreach my $line (@config) {
if (substr($line, 0, 1) eq '
push @out, $line;
next;
}
next if $line =~ /^[;\t ]+$/;
my ($option, $option_name);
if ($line =~ /^([A-Z]+[0-9]*)/) {
$option_name = lc $1;
$option = eval "\\\$$option_name";
my $value = eval "\${$option_name}";
if ($value) {
$$option = $value;
}
else {
$line = '; ' . $line;
$$option = undef;
}
}
elsif ($line =~ /^;+\s*([A-Z]+[0-9]*)/) {
$option_name = lc $1;
$option = eval "\\\$$option_name";
my $value = eval "\${$option_name}";
if ($value) {
$line =~ s/^;+\s*//;
$$option = $value == 1 ? '' : $value;
}
else {
$$option = undef;
}
}
if (defined $$option) {
push @out, "\U$option_name\E $$option\n"
unless grep { /^\U$option_name\E\b/; } @out;
}
else {
$line =~ s/\s*[^[:ascii:]]+\s*$//;
$line =~ s/[[:cntrl:]\s]+$//;
push(@out, "$line\n");
}
}
}
config();
my $file = join('', @out);
$file =~ s/\n{3,}/\n\n/g;
print $file;
__DATA__
FAVOURITEFRUIT banana
NEEDSPEELING
; SEEDSREMOVED
NUMBEROFBANANAS 48 | 81Update a configuration file
| 2perl
| n0kiw |
null | 79UTF-8 encode and decode
| 1lua
| 3dxzo |
foobar = 15
f x = x + foobar
where foobar = 15
f x = let foobar = 15
in x + foobar
f x = do
let foobar = 15
return $ x + foobar | 76Variables
| 8haskell
| n0eie |
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
public class UPC {
private static final int SEVEN = 7;
private static final Map<String, Integer> LEFT_DIGITS = Map.of(
" ## #", 0,
" ## #", 1,
" # ##", 2,
" #### #", 3,
" # ##", 4,
" ## #", 5,
" # ####", 6,
" ### ##", 7,
" ## ###", 8,
" # ##", 9
);
private static final Map<String, Integer> RIGHT_DIGITS = LEFT_DIGITS.entrySet()
.stream()
.collect(Collectors.toMap(
entry -> entry.getKey()
.replace(' ', 's')
.replace('#', ' ')
.replace('s', '#'),
Map.Entry::getValue
));
private static final String END_SENTINEL = "# #";
private static final String MID_SENTINEL = " # # ";
private static void decodeUPC(String input) {
Function<String, Map.Entry<Boolean, List<Integer>>> decode = (String candidate) -> {
int pos = 0;
var part = candidate.substring(pos, pos + END_SENTINEL.length());
List<Integer> output = new ArrayList<>();
if (END_SENTINEL.equals(part)) {
pos += END_SENTINEL.length();
} else {
return Map.entry(false, output);
}
for (int i = 1; i < SEVEN; i++) {
part = candidate.substring(pos, pos + SEVEN);
pos += SEVEN;
if (LEFT_DIGITS.containsKey(part)) {
output.add(LEFT_DIGITS.get(part));
} else {
return Map.entry(false, output);
}
}
part = candidate.substring(pos, pos + MID_SENTINEL.length());
if (MID_SENTINEL.equals(part)) {
pos += MID_SENTINEL.length();
} else {
return Map.entry(false, output);
}
for (int i = 1; i < SEVEN; i++) {
part = candidate.substring(pos, pos + SEVEN);
pos += SEVEN;
if (RIGHT_DIGITS.containsKey(part)) {
output.add(RIGHT_DIGITS.get(part));
} else {
return Map.entry(false, output);
}
}
part = candidate.substring(pos, pos + END_SENTINEL.length());
if (!END_SENTINEL.equals(part)) {
return Map.entry(false, output);
}
int sum = 0;
for (int i = 0; i < output.size(); i++) {
if (i % 2 == 0) {
sum += 3 * output.get(i);
} else {
sum += output.get(i);
}
}
return Map.entry(sum % 10 == 0, output);
};
Consumer<List<Integer>> printList = list -> {
var it = list.iterator();
System.out.print('[');
if (it.hasNext()) {
System.out.print(it.next());
}
while (it.hasNext()) {
System.out.print(", ");
System.out.print(it.next());
}
System.out.print(']');
};
var candidate = input.trim();
var out = decode.apply(candidate);
if (out.getKey()) {
printList.accept(out.getValue());
System.out.println();
} else {
StringBuilder builder = new StringBuilder(candidate);
builder.reverse();
out = decode.apply(builder.toString());
if (out.getKey()) {
printList.accept(out.getValue());
System.out.println(" Upside down");
} else if (out.getValue().size() == 12) {
System.out.println("Invalid checksum");
} else {
System.out.println("Invalid digit(s)");
}
}
}
public static void main(String[] args) {
var barcodes = List.of(
" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ",
" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ",
" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ",
" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ",
" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ",
" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ",
" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ",
" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ",
" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ",
" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # "
);
barcodes.forEach(UPC::decodeUPC);
}
} | 84UPC
| 9java
| 75frj |
require 'uri'
test_cases = [
,
,
,
,
,
,
,
,
,
,
,
,
,
]
class URI::Generic; alias_method :domain, :host; end
test_cases.each do |test_case|
puts test_case
uri = URI.parse(test_case)
%w[ scheme domain port path query fragment user password ].each do |attr|
puts if uri.send(attr)
end
end | 77URL parser
| 14ruby
| v9t2n |
use url::Url;
fn print_fields(url: Url) -> () {
println!("scheme: {}", url.scheme());
println!("username: {}", url.username());
if let Some(password) = url.password() {
println!("password: {}", password);
}
if let Some(domain) = url.domain() {
println!("domain: {}", domain);
}
if let Some(port) = url.port() {
println!("port: {}", port);
}
println!("path: {}", url.path());
if let Some(query) = url.query() {
println!("query: {}", query);
}
if let Some(fragment) = url.fragment() {
println!("fragment: {}", fragment);
}
}
fn main() {
let urls = vec![
"foo: | 77URL parser
| 15rust
| uczvj |
def van_eck():
n, seen, val = 0, {}, 0
while True:
yield val
last = {val: n}
val = n - seen.get(val, n)
seen.update(last)
n += 1
if __name__ == '__main__':
print(, list(islice(van_eck(), 10)))
print(, list(islice(van_eck(), 1000))[-10:]) | 74Van Eck sequence
| 3python
| 5lmux |
def print_all(*things):
for x in things:
print x | 67Variadic function
| 3python
| n8diz |
package main
import "fmt"
type vector struct {
x, y, z float64
}
var (
a = vector{3, 4, 5}
b = vector{4, 3, 5}
c = vector{-5, -12, -13}
)
func dot(a, b vector) float64 {
return a.x*b.x + a.y*b.y + a.z*b.z
}
func cross(a, b vector) vector {
return vector{a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y - a.y*b.x}
}
func s3(a, b, c vector) float64 {
return dot(a, cross(b, c))
}
func v3(a, b, c vector) vector {
return cross(a, cross(b, c))
}
func main() {
fmt.Println(dot(a, b))
fmt.Println(cross(a, b))
fmt.Println(s3(a, b, c))
fmt.Println(v3(a, b, c))
} | 72Vector products
| 0go
| 6fd3p |
RE = /\A[A-Z]{2}[A-Z0-9]{9}[0-9]{1}\z/
def valid_isin?(str)
return false unless str =~ RE
luhn(str.chars.map{|c| c.to_i(36)}.join)
end
p %w(US0378331005
US0373831005
U50378331005
US03378331005
AU0000XVGZA3
AU0000VXGZA3
FR0000988040).map{|tc| valid_isin?(tc) } | 71Validate International Securities Identification Number
| 14ruby
| 755ri |
null | 80URL decoding
| 11kotlin
| b7ckb |
<?php
$conf = file_get_contents('update-conf-file.txt');
$conf = preg_replace('/^(needspeeling)(|\s*\S*)$/mi', '; $1', $conf);
$conf = preg_replace('/^;?\s*(seedsremoved)/mi', '$1', $conf);
$conf = preg_replace('/^(numberofbananas)(|\s*\S*)$/mi', '$1 1024', $conf);
if (preg_match('/^;?\s*(numberofstrawberries)/mi', $conf, $matches)) {
$conf = preg_replace('/^(numberofstrawberries)(|\s*\S*)$/mi', '$1 62000', $conf);
} else {
$conf .= 'NUMBEROFSTRAWBERRIES 62000' . PHP_EOL;
}
echo $conf; | 81Update a configuration file
| 12php
| 753rp |
use strict;
use warnings;
use Unicode::UCD 'charinfo';
use utf8;
binmode STDOUT, ":encoding(UTF-8)";
my @chars = map {ord} qw/A /;
my $print_format = '%5s %-35s';
printf "$print_format%8s %s\n" , 'char', 'name', 'unicode', 'utf-8 encoding';
map{
my $name = charinfo($_)->{'name'};
printf "$print_format %06x " , chr, lc $name, $_;
my $utf8 = chr;
utf8::encode($utf8);
map{
printf "%x", ord;
} split //, $utf8;
print "\n";
} @chars; | 79UTF-8 encode and decode
| 2perl
| b7lk4 |
import java.net.URI
object WebAddressParser extends App {
parseAddress("foo: | 77URL parser
| 16scala
| gvy4i |
function encodeChar(chr)
return string.format("%%%X",string.byte(chr))
end
function encodeString(str)
local output, t = string.gsub(str,"[^%w]",encodeChar)
return output
end | 78URL encoding
| 1lua
| 8xk0e |
printallargs1 <- function(...) list(...)
printallargs1(1:5, "abc", TRUE) | 67Variadic function
| 13r
| 0x8sg |
def pairwiseOperation = { x, y, Closure binaryOp ->
assert x && y && x.size() == y.size()
[x, y].transpose().collect(binaryOp)
}
def pwMult = pairwiseOperation.rcurry { it[0] * it[1] }
def dotProduct = { x, y ->
assert x && y && x.size() == y.size()
pwMult(x, y).sum()
} | 72Vector products
| 7groovy
| d80n3 |
extern crate luhn_cc;
use luhn_cc::compute_luhn;
fn main() {
assert_eq!(validate_isin("US0378331005"), true);
assert_eq!(validate_isin("US0373831005"), false);
assert_eq!(validate_isin("U50378331005"), false);
assert_eq!(validate_isin("US03378331005"), false);
assert_eq!(validate_isin("AU0000XVGZA3"), true);
assert_eq!(validate_isin("AU0000VXGZA3"), true);
assert_eq!(validate_isin("FR0000988040"), true);
}
fn validate_isin(isin: &str) -> bool { | 71Validate International Securities Identification Number
| 15rust
| j4472 |
val LEFT_DIGITS = mapOf(
" ## #" to 0,
" ## #" to 1,
" # ##" to 2,
" #### #" to 3,
" # ##" to 4,
" ## #" to 5,
" # ####" to 6,
" ### ##" to 7,
" ## ###" to 8,
" # ##" to 9
)
val RIGHT_DIGITS = LEFT_DIGITS.mapKeys {
it.key.replace(' ', 's').replace('#', ' ').replace('s', '#')
}
const val END_SENTINEL = "# #"
const val MID_SENTINEL = " # # "
fun decodeUPC(input: String) {
fun decode(candidate: String): Pair<Boolean, List<Int>> {
var pos = 0
var part = candidate.slice(pos until pos + END_SENTINEL.length)
if (part == END_SENTINEL) {
pos += END_SENTINEL.length
} else {
return Pair(false, emptyList())
}
val output = mutableListOf<Int>()
for (i in 0 until 6) {
part = candidate.slice(pos until pos + 7)
pos += 7
if (LEFT_DIGITS.containsKey(part)) {
output.add(LEFT_DIGITS.getOrDefault(part, -1))
} else {
return Pair(false, output.toList())
}
}
part = candidate.slice(pos until pos + MID_SENTINEL.length)
if (part == MID_SENTINEL) {
pos += MID_SENTINEL.length
} else {
return Pair(false, output.toList())
}
for (i in 0 until 6) {
part = candidate.slice(pos until pos + 7)
pos += 7
if (RIGHT_DIGITS.containsKey(part)) {
output.add(RIGHT_DIGITS.getOrDefault(part, -1))
} else {
return Pair(false, output.toList())
}
}
part = candidate.slice(pos until pos + END_SENTINEL.length)
if (part == END_SENTINEL) {
pos += END_SENTINEL.length
} else {
return Pair(false, output.toList())
}
val sum = output.mapIndexed { i, v -> if (i % 2 == 0) v * 3 else v }.sum()
return Pair(sum % 10 == 0, output.toList())
}
val candidate = input.trim()
var out = decode(candidate)
if (out.first) {
println(out.second)
} else {
out = decode(candidate.reversed())
if (out.first) {
print(out.second)
println(" Upside down")
} else {
if (out.second.size == 12) {
println("Invalid checksum")
} else {
println("Invalid digit(s)")
}
}
}
}
fun main() {
val barcodes = listOf(
" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ",
" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ",
" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ",
" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ",
" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ",
" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ",
" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ",
" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ",
" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ",
" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ",
)
for (barcode in barcodes) {
decodeUPC(barcode)
}
} | 84UPC
| 11kotlin
| uc8vc |
package main
import "fmt"
func main() {
var s string
var i int
if _, err := fmt.Scan(&s, &i); err == nil && i == 75000 {
fmt.Println("good")
} else {
fmt.Println("wrong")
}
} | 83User input/Text
| 0go
| 93xmt |
int a;
double b;
AClassNameHere c; | 76Variables
| 9java
| qahxa |
[] unstack | 76Variables
| 10javascript
| isaol |
import Data.Monoid ((<>))
type Vector a = [a]
type Scalar a = a
a, b, c, d :: Vector Int
a = [3, 4, 5]
b = [4, 3, 5]
c = [-5, -12, -13]
d = [3, 4, 5, 6]
dot
:: (Num t)
=> Vector t -> Vector t -> Scalar t
dot u v
| length u == length v = sum $ zipWith (*) u v
| otherwise = error "Dotted Vectors must be of equal dimension."
cross
:: (Num t)
=> Vector t -> Vector t -> Vector t
cross u v
| length u == 3 && length v == 3 =
[ u !! 1 * v !! 2 - u !! 2 * v !! 1
, u !! 2 * head v - head u * v !! 2
, head u * v !! 1 - u !! 1 * head v
]
| otherwise = error "Crossed Vectors must both be three dimensional."
scalarTriple
:: (Num t)
=> Vector t -> Vector t -> Vector t -> Scalar t
scalarTriple q r s = dot q $ cross r s
vectorTriple
:: (Num t)
=> Vector t -> Vector t -> Vector t -> Vector t
vectorTriple q r s = cross q $ cross r s
main :: IO ()
main =
mapM_
putStrLn
[ "a . b = " <> show (dot a b)
, "a x b = " <> show (cross a b)
, "a . b x c = " <> show (scalarTriple a b c)
, "a x b x c = " <> show (vectorTriple a b c)
, "a . d = " <> show (dot a d)
] | 72Vector products
| 8haskell
| j457g |
object Isin extends App {
val isins = Seq("US0378331005", "US0373831005", "U50378331005",
"US03378331005", "AU0000XVGZA3","AU0000VXGZA3", "FR0000988040")
private def ISINtest(isin: String): Boolean = {
val isin0 = isin.trim.toUpperCase
def luhnTestS(number: String): Boolean = {
def luhnTestN(digits: Seq[Int]): Boolean = {
def checksum(digits: Seq[Int]): Int = {
digits.reverse.zipWithIndex
.foldLeft(0) {
case (sum, (digit, i)) =>
if (i % 2 == 0) sum + digit
else sum + (digit * 2) / 10 + (digit * 2) % 10
} % 10
}
checksum(digits) == 0
}
luhnTestN(number.map { c =>
assert(c.isDigit, s"$number has a non-digit error")
c.asDigit
})
}
if (!isin0.matches("^[A-Z]{2}[A-Z0-9]{9}\\d$")) false
else {
val sb = new StringBuilder
for (c <- isin0.substring(0, 12)) sb.append(Character.digit(c, 36))
luhnTestS(sb.toString)
}
}
isins.foreach(isin => println(f"$isin is ${if (ISINtest(isin)) "" else "not"}%s valid"))
} | 71Validate International Securities Identification Number
| 16scala
| b77k6 |
def vdc(n, base=2):
vdc, denom = 0,1
while n:
denom *= base
n, remainder = divmod(n, base)
vdc += remainder / denom
return vdc | 73Van der Corput sequence
| 3python
| 8xe0o |
word = System.in.readLine()
num = System.in.readLine().toInteger() | 83User input/Text
| 7groovy
| znpt5 |
import System.IO (hFlush, stdout)
main = do
putStr "Enter a string: "
hFlush stdout
str <- getLine
putStr "Enter an integer: "
hFlush stdout
num <- readLn :: IO Int
putStrLn $ str ++ (show num) | 83User input/Text
| 8haskell
| b7yk2 |
van_eck = Enumerator.new do |y|
ar = [0]
loop do
y << (term = ar.last)
ar << (ar.count(term)==1? 0: ar.size - 1 - ar[0..-2].rindex(term))
end
end
ve = van_eck.take(1000)
p ve.first(10), ve.last(10) | 74Van Eck sequence
| 14ruby
| gvc4q |
function decodeChar(hex)
return string.char(tonumber(hex,16))
end
function decodeString(str)
local output, t = string.gsub(str,"%%(%x%x)",decodeChar)
return output
end | 80URL decoding
| 1lua
| pjlbw |
import re
import string
DISABLED_PREFIX = ';'
class Option(object):
def __init__(self, name, value=None, disabled=False,
disabled_prefix=DISABLED_PREFIX):
self.name = str(name)
self.value = value
self.disabled = bool(disabled)
self.disabled_prefix = disabled_prefix
def __str__(self):
disabled = ('', '%s '% self.disabled_prefix)[self.disabled]
value = ('%s'% self.value, '')[self.value is None]
return ''.join((disabled, self.name, value))
def get(self):
enabled = not bool(self.disabled)
if self.value is None:
value = enabled
else:
value = enabled and self.value
return value
class Config(object):
reOPTION = r'^\s*(?P<disabled>%s*)\s*(?P<name>\w+)(?:\s+(?P<value>.+?))?\s*$'
def __init__(self, fname=None, disabled_prefix=DISABLED_PREFIX):
self.disabled_prefix = disabled_prefix
self.contents = []
self.options = {}
self.creOPTION = re.compile(self.reOPTION% self.disabled_prefix)
if fname:
self.parse_file(fname)
def __str__(self):
return '\n'.join(map(str, self.contents))
def parse_file(self, fname):
with open(fname) as f:
self.parse_lines(f)
return self
def parse_lines(self, lines):
for line in lines:
self.parse_line(line)
return self
def parse_line(self, line):
s = ''.join(c for c in line.strip() if c in string.printable)
moOPTION = self.creOPTION.match(s)
if moOPTION:
name = moOPTION.group('name').upper()
if not name in self.options:
self.add_option(name, moOPTION.group('value'),
moOPTION.group('disabled'))
else:
if not s.startswith(self.disabled_prefix):
self.contents.append(line.rstrip())
return self
def add_option(self, name, value=None, disabled=False):
name = name.upper()
opt = Option(name, value, disabled)
self.options[name] = opt
self.contents.append(opt)
return opt
def set_option(self, name, value=None, disabled=False):
name = name.upper()
opt = self.options.get(name)
if opt:
opt.value = value
opt.disabled = disabled
else:
opt = self.add_option(name, value, disabled)
return opt
def enable_option(self, name, value=None):
return self.set_option(name, value, False)
def disable_option(self, name, value=None):
return self.set_option(name, value, True)
def get_option(self, name):
opt = self.options.get(name.upper())
value = opt.get() if opt else None
return value
if __name__ == '__main__':
import sys
cfg = Config(sys.argv[1] if len(sys.argv) > 1 else None)
cfg.disable_option('needspeeling')
cfg.enable_option('seedsremoved')
cfg.enable_option('numberofbananas', 1024)
cfg.enable_option('numberofstrawberries', 62000)
print cfg | 81Update a configuration file
| 3python
| d8bn1 |
null | 76Variables
| 11kotlin
| 1h4pd |
fn van_eck_sequence() -> impl std::iter::Iterator<Item = i32> {
let mut index = 0;
let mut last_term = 0;
let mut last_pos = std::collections::HashMap::new();
std::iter::from_fn(move || {
let result = last_term;
let mut next_term = 0;
if let Some(v) = last_pos.get_mut(&last_term) {
next_term = index - *v;
*v = index;
} else {
last_pos.insert(last_term, index);
}
last_term = next_term;
index += 1;
Some(result)
})
}
fn main() {
let mut v = van_eck_sequence().take(1000);
println!("First 10 terms of the Van Eck sequence:");
for n in v.by_ref().take(10) {
print!("{} ", n);
}
println!("\nTerms 991 to 1000 of the Van Eck sequence:");
for n in v.skip(980) {
print!("{} ", n);
}
println!();
} | 74Van Eck sequence
| 15rust
| rulg5 |
object VanEck extends App {
def vanEck(n: Int): List[Int] = {
def vanEck(values: List[Int]): List[Int] =
if (values.size < n)
vanEck(math.max(0, values.indexOf(values.head, 1)) :: values)
else
values
vanEck(List(0)).reverse
}
val vanEck1000 = vanEck(1000)
println(s"The first 10 terms are ${vanEck1000.take(10)}.")
println(s"Terms 991 to 1000 are ${vanEck1000.drop(990)}.")
} | 74Van Eck sequence
| 16scala
| hguja |
use Wx;
package MyApp;
use base 'Wx::App';
use Wx qw(wxHORIZONTAL wxVERTICAL wxALL wxALIGN_CENTER);
use Wx::Event 'EVT_BUTTON';
our ($frame, $text_input, $integer_input);
sub OnInit
{$frame = new Wx::Frame
(undef, -1, 'Input window', [-1, -1], [250, 150]);
my $panel = new Wx::Panel($frame, -1);
$text_input = new Wx::TextCtrl($panel, -1, '');
$integer_input = new Wx::SpinCtrl
($panel, -1, '', [-1, -1], [-1, -1],
0, 0, 100_000);
my $okay_button = new Wx::Button($panel, -1, 'OK');
EVT_BUTTON($frame, $okay_button, \&OnQuit);
my $sizer = new Wx::BoxSizer(wxVERTICAL);
$sizer->Add($_, 0, wxALL | wxALIGN_CENTER, 5)
foreach $text_input, $integer_input, $okay_button;
$panel->SetSizer($sizer);
$frame->Show(1);}
sub OnQuit
{print 'String: ', $text_input->GetValue, "\n";
print 'Integer: ', $integer_input->GetValue, "\n";
$frame->Close;}
package main;
MyApp->new->MainLoop; | 82User input/Graphical
| 2perl
| 3dazs |
from unicodedata import name
def unicode_code(ch):
return 'U+{:04x}'.format(ord(ch))
def utf8hex(ch):
return .join([hex(c)[2:] for c in ch.encode('utf8')]).upper()
if __name__ == :
print('{:<11} {:<36} {:<15} {:<15}'.format('Character', 'Name', 'Unicode', 'UTF-8 encoding (hex)'))
chars = ['A', '', '', '', '']
for char in chars:
print('{:<11} {:<36} {:<15} {:<15}'.format(char, name(char), unicode_code(char), utf8hex(char))) | 79UTF-8 encode and decode
| 3python
| pj2bm |
def print_all(*things)
puts things
end | 67Variadic function
| 14ruby
| fitdr |
null | 67Variadic function
| 15rust
| tnzfd |
public class VectorProds{
public static class Vector3D<T extends Number>{
private T a, b, c;
public Vector3D(T a, T b, T c){
this.a = a;
this.b = b;
this.c = c;
}
public double dot(Vector3D<?> vec){
return (a.doubleValue() * vec.a.doubleValue() +
b.doubleValue() * vec.b.doubleValue() +
c.doubleValue() * vec.c.doubleValue());
}
public Vector3D<Double> cross(Vector3D<?> vec){
Double newA = b.doubleValue()*vec.c.doubleValue() - c.doubleValue()*vec.b.doubleValue();
Double newB = c.doubleValue()*vec.a.doubleValue() - a.doubleValue()*vec.c.doubleValue();
Double newC = a.doubleValue()*vec.b.doubleValue() - b.doubleValue()*vec.a.doubleValue();
return new Vector3D<Double>(newA, newB, newC);
}
public double scalTrip(Vector3D<?> vecB, Vector3D<?> vecC){
return this.dot(vecB.cross(vecC));
}
public Vector3D<Double> vecTrip(Vector3D<?> vecB, Vector3D<?> vecC){
return this.cross(vecB.cross(vecC));
}
@Override
public String toString(){
return "<" + a.toString() + ", " + b.toString() + ", " + c.toString() + ">";
}
}
public static void main(String[] args){
Vector3D<Integer> a = new Vector3D<Integer>(3, 4, 5);
Vector3D<Integer> b = new Vector3D<Integer>(4, 3, 5);
Vector3D<Integer> c = new Vector3D<Integer>(-5, -12, -13);
System.out.println(a.dot(b));
System.out.println(a.cross(b));
System.out.println(a.scalTrip(b, c));
System.out.println(a.vecTrip(b, c));
}
} | 72Vector products
| 9java
| uc9vv |
def vdc(n, base=2)
str = n.to_s(base).reverse
str.to_i(base).quo(base ** str.length)
end
(2..5).each do |base|
puts + Array.new(10){|i| vdc(i,base)}.join()
end | 73Van der Corput sequence
| 14ruby
| isxoh |
use strict;
use warnings;
use feature 'say';
sub decode_UPC {
my($line) = @_;
my(%pattern_to_digit_1,%pattern_to_digit_2,@patterns1,@patterns2,@digits,$sum);
for my $p ('
push @patterns1, $p;
push @patterns2, $p =~ tr/
}
$pattern_to_digit_1{$patterns1[$_]} = $_ for 0..$
$pattern_to_digit_2{$patterns2[$_]} = $_ for 0..$
my $re = '\s*
"(?<match1>(?:@{[join '|', @patterns1]}){6})" .
'\s*
"(?<match2>(?:@{[join '|', @patterns2]}){6})" .
'\s*
$line =~ /^$re$/g || return;
my($match1,$match2) = ($+{match1}, $+{match2});
push @digits, $pattern_to_digit_1{$_} for $match1 =~ /(.{7})/g;
push @digits, $pattern_to_digit_2{$_} for $match2 =~ /(.{7})/g;
$sum += (3,1)[$_%2] * $digits[$_] for 0..11;
$sum % 10 ? '' : join '', @digits;
}
my @lines = (
'
'
'
'
'
'
'
'
'
'
);
for my $line (@lines) {
say decode_UPC($line)
// decode_UPC(join '', reverse split '', $line)
// 'Invalid';
} | 84UPC
| 2perl
| 8x40w |
import java.util.Scanner;
public class GetInput {
public static void main(String[] args) throws Exception {
Scanner s = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = s.nextLine();
System.out.print("Enter an integer: ");
int i = Integer.parseInt(s.next());
}
} | 83User input/Text
| 9java
| gvd4m |
struct VanEckSequence: Sequence, IteratorProtocol {
private var index = 0
private var lastTerm = 0
private var lastPos = Dictionary<Int, Int>()
mutating func next() -> Int? {
let result = lastTerm
var nextTerm = 0
if let v = lastPos[lastTerm] {
nextTerm = index - v
}
lastPos[lastTerm] = index
lastTerm = nextTerm
index += 1
return result
}
}
let seq = VanEckSequence().prefix(1000)
print("First 10 terms of the Van Eck sequence:")
for n in seq.prefix(10) {
print(n, terminator: " ")
}
print("\nTerms 991 to 1000 of the Van Eck sequence:")
for n in seq.dropFirst(990) {
print(n, terminator: " ")
}
print() | 74Van Eck sequence
| 17swift
| 4295g |
def printAll(args: Any*) = args foreach println | 67Variadic function
| 16scala
| 6ty31 |
function dotProduct() {
var len = arguments[0] && arguments[0].length;
var argsLen = arguments.length;
var i, j = len;
var prod, sum = 0; | 72Vector products
| 10javascript
| 75urd |
null | 73Van der Corput sequence
| 15rust
| n0qi4 |
object VanDerCorput extends App {
def compute(n: Int, base: Int = 2) =
Iterator.from(0).
scanLeft(1)((a, _) => a * base).
map(b => (n - 1) / b -> b).
takeWhile(_._1 != 0).
foldLeft(0d)((a, b) => a + (b._1 % base).toDouble / b._2 / base)
val n = scala.io.StdIn.readInt
val b = scala.io.StdIn.readInt
(1 to n).foreach(x => println(compute(x, b)))
} | 73Van der Corput sequence
| 16scala
| ti8fb |
require 'stringio'
class ConfigFile
def self.file(filename)
fh = File.open(filename)
obj = self.new(fh)
obj.filename = filename
fh.close
obj
end
def self.data(string)
fh = StringIO.new(string)
obj = self.new(fh)
fh.close
obj
end
def initialize(filehandle)
@lines = filehandle.readlines
@filename = nil
tidy_file
end
attr :filename
def save()
if @filename
File.open(@filename, ) {|f| f.write(self)}
end
end
def tidy_file()
@lines.map! do |line|
line.lstrip!
if line.match(/^
line
else
line.sub!(/^;+\s+/, )
if line.match(/^; \s*$/)
line =
else
line = line.rstrip +
if m = line.match(/^(; )?([[:upper:]]+)\s+(.*)/)
line = (m[1].nil?? : m[1]) + format_line(m[2], m[3])
end
end
line
end
end
end
def format_line(option, value)
% [option.upcase.strip, value.nil?? : + value.to_s.strip]
end
def find_option(option)
@lines.find_index {|line| line.match(/^
end
def enable_option(option)
if idx = find_option( + option)
@lines[idx][/^; /] =
end
end
def disable_option(option)
if idx = find_option(option)
@lines[idx][/^/] =
end
end
def set_value(option, value)
if idx = find_option(option)
@lines[idx] = format_line(option, value)
else
@lines << format_line(option, value)
end
end
def to_s
@lines.join('')
end
end
config = ConfigFile.data(DATA.read)
config.disable_option('needspeeling')
config.enable_option('seedsremoved')
config.set_value('numberofbananas', 1024)
config.set_value('numberofstrawberries', 62000)
puts config
__END__
FAVOURITEFRUIT banana
NEEDSPEELING
;;; SEEDSREMOVED
;;;
NUMBEROFBANANAS 48 | 81Update a configuration file
| 14ruby
| ti1f2 |
WScript.Echo("Enter a string");
var str = WScript.StdIn.ReadLine();
var val = 0;
while (val != 75000) {
WScript.Echo("Enter the integer 75000");
val = parseInt( WScript.StdIn.ReadLine() );
} | 83User input/Text
| 10javascript
| kr6hq |
character_arr = [,,,,]
for c in character_arr do
puts + c.encode()
puts utf-8
puts + c.each_byte.map { |n| '%02X ' % (n & 0xFF) }.join
puts
end | 79UTF-8 encode and decode
| 14ruby
| aku1s |
fn main() {
let chars = vec!('A', '', '', '', '');
chars.iter().for_each(|c| {
let mut encoded = vec![0; c.len_utf8()];
c.encode_utf8(&mut encoded);
let decoded = String::from_utf8(encoded.to_vec()).unwrap();
let encoded_string = encoded.iter().fold(String::new(), |acc, val| format!("{}{:X}", acc, val));
println!("Character: {}, Unicode:{}, UTF-8 encoded:{}, Decoded: {}", c, c.escape_unicode(), encoded_string , decoded);
});
} | 79UTF-8 encode and decode
| 15rust
| eb5aj |
sub urlencode {
my $s = shift;
$s =~ s/([^-A-Za-z0-9_.!~*'() ])/sprintf("%%%02X", ord($1))/eg;
$s =~ tr/ /+/;
return $s;
}
print urlencode('http://foo bar/')."\n"; | 78URL encoding
| 2perl
| 5lzu2 |
func printAll<T>(things: T...) { | 67Variadic function
| 17swift
| dofnh |
object UTF8EncodeAndDecode extends App {
val codePoints = Seq(0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E)
def utf8Encode(codepoint: Int): Array[Byte] =
new String(Array[Int](codepoint), 0, 1).getBytes(StandardCharsets.UTF_8)
def utf8Decode(bytes: Array[Byte]): Int =
new String(bytes, StandardCharsets.UTF_8).codePointAt(0)
println("Char Name Unicode UTF-8 Decoded")
for (codePoint <- codePoints) {
val w = if (Character.isBmpCodePoint(codePoint)) 4 else 5 | 79UTF-8 encode and decode
| 16scala
| qarxw |
a = 1 | 76Variables
| 1lua
| akg1v |
func vanDerCorput(n: Int, base: Int, num: inout Int, denom: inout Int) {
var n = n, p = 0, q = 1
while n!= 0 {
p = p * base + (n% base)
q *= base
n /= base
}
num = p
denom = q
while p!= 0 {
n = p
p = q% p
q = n
}
num /= q
denom /= q
}
var num = 0
var denom = 0
for base in 2...5 {
print("base \(base): 0 ", terminator: "")
for n in 1..<10 {
vanDerCorput(n: n, base: base, num: &num, denom: &denom)
print("\(num)/\(denom) ", terminator: "")
}
print()
} | 73Van der Corput sequence
| 17swift
| oqw8k |
import itertools
import re
RE_BARCODE = re.compile(
r
r
r
r
r
r
r
)
LEFT_DIGITS = {
(0, 0, 0, 1, 1, 0, 1): 0,
(0, 0, 1, 1, 0, 0, 1): 1,
(0, 0, 1, 0, 0, 1, 1): 2,
(0, 1, 1, 1, 1, 0, 1): 3,
(0, 1, 0, 0, 0, 1, 1): 4,
(0, 1, 1, 0, 0, 0, 1): 5,
(0, 1, 0, 1, 1, 1, 1): 6,
(0, 1, 1, 1, 0, 1, 1): 7,
(0, 1, 1, 0, 1, 1, 1): 8,
(0, 0, 0, 1, 0, 1, 1): 9,
}
RIGHT_DIGITS = {
(1, 1, 1, 0, 0, 1, 0): 0,
(1, 1, 0, 0, 1, 1, 0): 1,
(1, 1, 0, 1, 1, 0, 0): 2,
(1, 0, 0, 0, 0, 1, 0): 3,
(1, 0, 1, 1, 1, 0, 0): 4,
(1, 0, 0, 1, 1, 1, 0): 5,
(1, 0, 1, 0, 0, 0, 0): 6,
(1, 0, 0, 0, 1, 0, 0): 7,
(1, 0, 0, 1, 0, 0, 0): 8,
(1, 1, 1, 0, 1, 0, 0): 9,
}
MODULES = {
: 0,
: 1,
}
DIGITS_PER_SIDE = 6
MODULES_PER_DIGIT = 7
class ParityError(Exception):
class ChecksumError(Exception):
def group(iterable, n):
args = [iter(iterable)] * n
return tuple(itertools.zip_longest(*args))
def parse(barcode):
match = RE_BARCODE.match(barcode)
left = group((MODULES[c] for c in match.group()), MODULES_PER_DIGIT)
right = group((MODULES[c] for c in match.group()), MODULES_PER_DIGIT)
left, right = check_parity(left, right)
return tuple(
itertools.chain(
(LEFT_DIGITS[d] for d in left),
(RIGHT_DIGITS[d] for d in right),
)
)
def check_parity(left, right):
left_parity = sum(sum(d)% 2 for d in left)
right_parity = sum(sum(d)% 2 for d in right)
if left_parity == 0 and right_parity == DIGITS_PER_SIDE:
_left = tuple(tuple(reversed(d)) for d in reversed(right))
right = tuple(tuple(reversed(d)) for d in reversed(left))
left = _left
elif left_parity != DIGITS_PER_SIDE or right_parity != 0:
error = tuple(
itertools.chain(
(LEFT_DIGITS.get(d, ) for d in left),
(RIGHT_DIGITS.get(d, ) for d in right),
)
)
raise ParityError(.join(str(d) for d in error))
return left, right
def checksum(digits):
odds = (digits[i] for i in range(0, 11, 2))
evens = (digits[i] for i in range(1, 10, 2))
check_digit = (sum(odds) * 3 + sum(evens))% 10
if check_digit != 0:
check_digit = 10 - check_digit
if digits[-1] != check_digit:
raise ChecksumError(str(check_digit))
return check_digit
def main():
barcodes = [
,
,
,
,
,
,
,
,
,
,
,
]
for barcode in barcodes:
try:
digits = parse(barcode)
except ParityError as err:
print(f)
continue
try:
check_digit = checksum(digits)
except ChecksumError as err:
print(f)
continue
print(f)
if __name__ == :
main() | 84UPC
| 3python
| oqg81 |
null | 83User input/Text
| 11kotlin
| 2m0li |
<?php
$s = 'http:
$s = rawurlencode($s);
?> | 78URL encoding
| 12php
| oqb85 |
null | 72Vector products
| 11kotlin
| 93zmh |
import Tkinter,tkSimpleDialog
root = Tkinter.Tk()
root.withdraw()
number = tkSimpleDialog.askinteger(, )
string = tkSimpleDialog.askstring(, ) | 82User input/Graphical
| 3python
| 6fe3w |
import Foundation
func encode(_ scalar: UnicodeScalar) -> Data {
return Data(String(scalar).utf8)
}
func decode(_ data: Data) -> UnicodeScalar? {
guard let string = String(data: data, encoding: .utf8) else {
assertionFailure("Failed to convert data to a valid String")
return nil
}
assert(string.unicodeScalars.count == 1, "Data should contain one scalar!")
return string.unicodeScalars.first
}
for scalar in "A".unicodeScalars {
let bytes = encode(scalar)
let formattedBytes = bytes.map({ String($0, radix: 16)}).joined(separator: " ")
let decoded = decode(bytes)!
print("character: \(decoded), code point: U+\(String(scalar.value, radix: 16)), \tutf-8: \(formattedBytes)")
} | 79UTF-8 encode and decode
| 17swift
| 1hvpt |
sub urldecode {
my $s = shift;
$s =~ tr/\+/ /;
$s =~ s/\%([A-Fa-f0-9]{2})/pack('C', hex($1))/eg;
return $s;
}
print urldecode('http%3A%2F%2Ffoo+bar%2F')."\n"; | 80URL decoding
| 2perl
| 6fx36 |
library(gWidgets)
options(guiToolkit="RGtk2")
w <- gwindow("Enter a string and a number")
lyt <- glayout(cont=w)
lyt[1,1] <- "Enter a string"
lyt[1,2] <- gedit("", cont=lyt)
lyt[2,1] <- "Enter 75000"
lyt[2,2] <- gedit("", cont=lyt)
lyt[3,2] <- gbutton("validate", cont=lyt, handler=function(h,...) {
txt <- svalue(lyt[1,2])
x <- svalue(lyt[2,2])
x <- gsub(",", "", x)
x <- as.integer(x)
if(nchar(txt) > 0 && x == 75000)
gmessage("Congratulations, you followed directions", parent=w)
else
gmessage("You failed this simple task", parent=w)
}) | 82User input/Graphical
| 13r
| fobdc |
import urllib
s = 'http:
s = urllib.quote(s) | 78URL encoding
| 3python
| 4235k |
URLencode("http://foo bar/") | 78URL encoding
| 13r
| 2mdlg |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.