code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
use XML::XPath qw();
my $x = XML::XPath->new('<inventory ... </inventory>');
[$x->findnodes('//item[1]')->get_nodelist]->[0];
print $x->findnodes_as_string('//price');
$x->findnodes('//name')->get_nodelist; | 23XML/XPath
| 2perl
| vb20 |
def zNum( n:BigInt ) : String = {
if( n == 0 ) return "0" | 16Zeckendorf number representation
| 16scala
| w9es |
<?php
$doc = DOMDocument::loadXML('<inventory title=>...</inventory>');
$xpath = new DOMXPath($doc);
$nodelist = $xpath->query('
$result = $nodelist->item(0);
$nodelist = $xpath->query('
for($i = 0; $i < $nodelist->length; $i++)
{
print $doc->saveXML($nodelist->item($i)).;
}
$nodelist = $xpath->query('
$result = array();
foreach($nodelist as $node)
{
$result[] = $node;
} | 23XML/XPath
| 12php
| 06sp |
y = ( 5**4**3**2 ).to_s
puts | 18Arbitrary-precision integers (included)
| 14ruby
| yk6n |
int[] array = new int[10]; | 13Arrays
| 9java
| 8g06 |
package main
import (
"fmt"
"strconv"
)
func zz(n int) []int {
r := make([]int, n*n)
i := 0
n2 := n * 2
for d := 1; d <= n2; d++ {
x := d - n
if x < 0 {
x = 0
}
y := d - 1
if y > n-1 {
y = n - 1
}
j := n2 - d
if j > d {
j = d
}
for k := 0; k < j; k++ {
if d&1 == 0 {
r[(x+k)*n+y-k] = i
} else {
r[(y-k)*n+x+k] = i
}
i++
}
}
return r
}
func main() {
const n = 5
w := len(strconv.Itoa(n*n - 1))
for i, e := range zz(n) {
fmt.Printf("%*d ", w, e)
if i%n == n-1 {
fmt.Println("")
}
}
} | 27Zig-zag matrix
| 0go
| 2rl7 |
extern crate num;
use num::bigint::BigUint;
use num::FromPrimitive;
use num::pow::pow;
fn main() {
let big = BigUint::from_u8(5).unwrap();
let answer_as_string = format!("{}", pow(big,pow(4,pow(3,2)))); | 18Arbitrary-precision integers (included)
| 15rust
| mbya |
null | 13Arrays
| 10javascript
| fkdg |
from xml.dom import minidom
xmlfile = file()
xmldoc = minidom.parse(xmlfile).documentElement
xmldoc = minidom.parseString(OmniCorp Store
i = xmldoc.getElementsByTagName()
firstItemElement = i[0]
for j in xmldoc.getElementsByTagName():
print j.childNodes[0].data
namesArray = xmldoc.getElementsByTagName() | 23XML/XPath
| 3python
| upvd |
library("XML")
doc <- xmlInternalTreeParse("test3.xml")
getNodeSet(doc, "//item")[[1]]
sapply(getNodeSet(doc, "//price"), xmlValue)
sapply(getNodeSet(doc, "//name"), xmlValue) | 23XML/XPath
| 13r
| cj95 |
def zz = { n ->
grid = new int[n][n]
i = 0
for (d in 1..n*2) {
(x, y) = [Math.max(0, d - n), Math.min(n - 1, d - 1)]
Math.min(d, n*2 - d).times {
grid[d%2?y-it:x+it][d%2?x+it:y-it] = i++;
}
}
grid
} | 27Zig-zag matrix
| 7groovy
| yv6o |
scala> BigInt(5) modPow (BigInt(4) pow (BigInt(3) pow 2).toInt, BigInt(10) pow 20)
res21: scala.math.BigInt = 92256259918212890625
scala> (BigInt(5) pow (BigInt(4) pow (BigInt(3) pow 2).toInt).toInt).toString
res22: String = 6206069878660874470748320557284679309194219265199117173177383244
78446890420544620839553285931321349485035253770303663683982841794590287939217907
89641300156281305613064874236198955114921296922487632406742326659692228562195387
46210423235340883954495598715281862895110697243759768434501295076608139350684049
01191160699929926568099301259938271975526587719565309995276438998093283175080241
55833224724855977970015112594128926594587205662421861723789001208275184293399910
13912158886504596553858675842231519094813553261073608575593794241686443569888058
92732524316323249492420512640962691673104618378381545202638771401061171968052873
21414945463925055899307933774904078819911387324217976311238875802878310483037255
33789567769926391314746986316354035923183981697660495275234703657750678459919...
scala> res22 take 20
res23: String = 62060698786608744707
scala> res22 length
res24: Int = 183231
scala> | 18Arbitrary-precision integers (included)
| 16scala
| lacq |
import Data.Array (Array, array, bounds, range, (!))
import Text.Printf (printf)
import Data.List (sortBy)
compZig :: (Int, Int) -> (Int, Int) -> Ordering
compZig (x, y) (x_, y_) = compare (x + y) (x_ + y_) <> go x y
where
go x y
| even (x + y) = compare x x_
| otherwise = compare y y_
zigZag :: (Int, Int) -> Array (Int, Int) Int
zigZag upper = array b $ zip (sortBy compZig (range b)) [0 ..]
where
b = ((0, 0), upper) | 27Zig-zag matrix
| 8haskell
| a01g |
require
include REXML
doc = Document.new(
%q@<inventory title=>
...
</inventory>
@
)
invisibility = XPath.first( doc, )
XPath.each( doc, ) { |element| puts element.text }
names = XPath.match( doc, ) | 23XML/XPath
| 14ruby
| 4a5p |
scala> val xml: scala.xml.Elem =
| <inventory title="OmniCorp Store #45x10^3">
| <section name="health">
| <item upc="123456789" stock="12">
| <name>Invisibility Cream</name>
| <price>14.50</price>
| <description>Makes you invisible</description>
| </item>
| <item upc="445322344" stock="18">
| <name>Levitation Salve</name>
| <price>23.99</price>
| <description>Levitate yourself for up to 3 hours per application</description>
| </item>
| </section>
| <section name="food">
| <item upc="485672034" stock="653">
| <name>Blork and Freen Instameal</name>
| <price>4.95</price>
| <description>A tasty meal in a tablet; just add water</description>
| </item>
| <item upc="132957764" stock="44">
| <name>Grob winglets</name>
| <price>3.56</price>
| <description>Tender winglets of Grob. Just add water</description>
| </item>
| </section>
| </inventory>
scala> val firstItem = xml \\ "item" take 1
firstItem: scala.xml.NodeSeq =
NodeSeq(<item upc="123456789" stock="12">
<name>Invisibility Cream</name>
<price>14.50</price>
<description>Makes you invisible</description>
</item>)
scala> xml \\ "price" map (_.text) foreach println
14.50
23.99
4.95
3.56
scala> val names = (xml \\ "name").toArray
names: Array[scala.xml.Node] = Array(<name>Invisibility Cream</name>, <name>Levitation Salve</name>, <name>Blork and Freen Instameal</name>, <name>Grob winglets</name>) | 23XML/XPath
| 16scala
| jq7i |
sub circle {
my ($radius, $cx, $cy, $fill, $stroke) = @_;
print "<circle cx='$cx' cy='$cy' r='$radius' ",
"fill='$fill' stroke='$stroke' stroke-width='1'/>\n";
}
sub yin_yang {
my ($rad, $cx, $cy, %opt) = @_;
my ($c, $w) = (1, 0);
$opt{fill} //= 'white';
$opt{stroke} //= 'black';
$opt{recurangle} //= 0;
print "<g transform='rotate($opt{angle}, $cx, $cy)'>"
if $opt{angle};
if ($opt{flip}) { ($c, $w) = ($w, $c) };
circle($rad, $cx, $cy, $opt{fill}, $opt{stroke});
print "<path d='M $cx ", $cy + $rad, "A ",
$rad/2, " ", $rad/2, " 0 0 $c $cx $cy ",
$rad/2, " ", $rad/2, " 0 0 $w $cx ", $cy - $rad, " ",
$rad, " ", $rad, " 0 0 $c $cx ", $cy + $rad, " ",
"z' fill='$opt{stroke}' stroke='none' />";
if ($opt{recur} and $rad > 1) {
yin_yang($rad/4, $cx, $cy + $rad/2, %opt,
angle => $opt{recurangle},
fill => $opt{stroke},
stroke => $opt{fill} );
yin_yang($rad/4, $cx, $cy - $rad/2, %opt,
angle => 180 + $opt{recurangle});
} else {
circle($rad/5, $cx, $cy + $rad/2, $opt{fill}, $opt{stroke});
circle($rad/5, $cx, $cy - $rad/2, $opt{stroke}, $opt{fill});
}
print "</g>" if $opt{angle};
}
print <<'HEAD';
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1"
xmlns:xlink="http://www.w3.org/1999/xlink">
HEAD
yin_yang(200, 250, 250, recur=>1,
angle=>0, recurangle=>90, fill=>'white', stroke=>'black');
yin_yang(100, 500, 500);
print "</svg>" | 26Yin and yang
| 2perl
| 7arh |
fun main(x: Array<String>) {
var a = arrayOf(1, 2, 3, 4)
println(a.asList())
a += 5
println(a.asList())
println(a.reversedArray().asList())
} | 13Arrays
| 11kotlin
| w2ek |
use utf8;
use strict;
binmode STDOUT, ":utf8";
my (@tgt, %names);
sub setprops {
my %h = @_;
my @p = keys %h;
for my $p (@p) {
my @v = @{ $h{$p} };
@tgt = map(+{idx=>$_-1, map{ ($_, undef) } @p}, 1 .. @v)
unless @tgt;
$names{$_} = $p for @v;
}
}
my $solve = sub {
for my $i (@tgt) {
printf("%12s", ucfirst($i->{$_} // "Qu?"))
for reverse sort keys %$i;
print "\n";
}
"there is only one"
};
sub pair {
my ($a, $b, @v) = @_;
if ($a =~ /^(\d+)$/) {
$tgt[$1]{ $names{$b} } = $b;
return;
}
@v = (0) unless @v;
my %allowed;
$allowed{$_} = 1 for @v;
my ($p1, $p2) = ($names{$a}, $names{$b});
my $e = $solve;
$solve = sub {
my ($x, $y);
($x) = grep { $_->{$p1} eq $a } @tgt;
($y) = grep { $_->{$p2} eq $b } @tgt;
$x and $y and
return $allowed{ $x->{idx} - $y->{idx} } && $e->();
my $try_stuff = sub {
my ($this, $p, $v, $sign) = @_;
for (@v) {
my $i = $this->{idx} + $sign * $_;
next unless $i >= 0 && $i < @tgt && !$tgt[$i]{$p};
local $tgt[$i]{$p} = $v;
$e->() and return 1;
}
return
};
$x and return $try_stuff->($x, $p2, $b, 1);
$y and return $try_stuff->($y, $p1, $a, -1);
for $x (@tgt) {
next if $x->{$p1};
local $x->{$p1} = $a;
$try_stuff->($x, $p2, $b, 1) and return 1;
}
};
}
setprops (
'Who' => [ qw(Deutsch Svensk Norske Danske AEnglisk) ],
'Pet' => [ qw(birds dog horse zebra cats) ],
'Drink' => [ qw(water tea milk beer coffee) ],
'Smoke' => [ qw(dunhill blue_master prince blend pall_mall) ],
'Color' => [ qw(red green yellow white blue) ]
);
pair qw( AEnglisk red );
pair qw( Svensk dog );
pair qw( Danske tea );
pair qw( green white 1 );
pair qw( coffee green );
pair qw( pall_mall birds );
pair qw( yellow dunhill );
pair qw( 2 milk );
pair qw( 0 Norske );
pair qw( blend cats -1 1 );
pair qw( horse dunhill -1 1 );
pair qw( blue_master beer );
pair qw( Deutsch prince );
pair qw( Norske blue -1 1 );
pair qw( water blend -1 1 );
$solve->(); | 24Zebra puzzle
| 2perl
| 2hlf |
package main
import "fmt"
type Func func(int) int
type FuncFunc func(Func) Func
type RecursiveFunc func (RecursiveFunc) Func
func main() {
fac := Y(almost_fac)
fib := Y(almost_fib)
fmt.Println("fac(10) = ", fac(10))
fmt.Println("fib(10) = ", fib(10))
}
func Y(f FuncFunc) Func {
g := func(r RecursiveFunc) Func {
return f(func(x int) int {
return r(r)(x)
})
}
return g(g)
}
func almost_fac(f Func) Func {
return func(x int) int {
if x <= 1 {
return 1
}
return x * f(x-1)
}
}
func almost_fib(f Func) Func {
return func(x int) int {
if x <= 2 {
return 1
}
return f(x-1)+f(x-2)
}
} | 25Y combinator
| 0go
| o68q |
public static int[][] Zig_Zag(final int size)
{
int[][] data = new int[size][size];
int i = 1;
int j = 1;
for (int element = 0; element < size * size; element++)
{
data[i - 1][j - 1] = element;
if ((i + j) % 2 == 0)
{ | 27Zig-zag matrix
| 9java
| ja7c |
def Y = { le -> ({ f -> f(f) })({ f -> le { x -> f(f)(x) } }) }
def factorial = Y { fac ->
{ n -> n <= 2 ? n: n * fac(n - 1) }
}
assert 2432902008176640000 == factorial(20G)
def fib = Y { fibStar ->
{ n -> n <= 1 ? n: fibStar(n - 1) + fibStar(n - 2) }
}
assert fib(10) == 55 | 25Y combinator
| 7groovy
| xdwl |
function ZigZagMatrix(n) {
this.height = n;
this.width = n;
this.mtx = [];
for (var i = 0; i < n; i++)
this.mtx[i] = [];
var i=1, j=1;
for (var e = 0; e < n*n; e++) {
this.mtx[i-1][j-1] = e;
if ((i + j) % 2 == 0) { | 27Zig-zag matrix
| 10javascript
| 1sp7 |
newtype Mu a = Roll
{ unroll :: Mu a -> a }
fix :: (a -> a) -> a
fix = g <*> (Roll . g)
where
g = (. (>>= id) unroll)
- this version is not in tail call position...
fac :: Integer -> Integer
fac =
(fix $ \f n i -> if i <= 0 then n else f (i * n) (i - 1)) 1
fibs :: () -> [Integer]
fibs() = 0: 1: fix fibs_ 0 1
where
fibs_ fnc f s =
case f + s of n -> n `seq` n: fnc s n
main :: IO ()
main =
mapM_
print
[ map fac [1 .. 20]
, take 20 $ fibs()
] | 25Y combinator
| 8haskell
| 2jll |
import math
def yinyang(n=3):
radii = [i * n for i in (1, 3, 6)]
ranges = [list(range(-r, r+1)) for r in radii]
squares = [[ (x,y) for x in rnge for y in rnge]
for rnge in ranges]
circles = [[ (x,y) for x,y in sqrpoints
if math.hypot(x,y) <= radius ]
for sqrpoints, radius in zip(squares, radii)]
m = {(x,y):' ' for x,y in squares[-1]}
for x,y in circles[-1]:
m[x,y] = '*'
for x,y in circles[-1]:
if x>0: m[(x,y)] = ''
for x,y in circles[-2]:
m[(x,y+3*n)] = '*'
m[(x,y-3*n)] = ''
for x,y in circles[-3]:
m[(x,y+3*n)] = ''
m[(x,y-3*n)] = '*'
return '\n'.join(''.join(m[(x,y)] for x in reversed(ranges[-1])) for y in ranges[-1]) | 26Yin and yang
| 3python
| je7p |
import java.util.function.Function;
public interface YCombinator {
interface RecursiveFunction<F> extends Function<RecursiveFunction<F>, F> { }
public static <A,B> Function<A,B> Y(Function<Function<A,B>, Function<A,B>> f) {
RecursiveFunction<Function<A,B>> r = w -> f.apply(x -> w.apply(w).apply(x));
return r.apply(r);
}
public static void main(String... arguments) {
Function<Integer,Integer> fib = Y(f -> n ->
(n <= 2)
? 1
: (f.apply(n - 1) + f.apply(n - 2))
);
Function<Integer,Integer> fac = Y(f -> n ->
(n <= 1)
? 1
: (n * f.apply(n - 1))
);
System.out.println("fib(10) = " + fib.apply(10));
System.out.println("fac(10) = " + fac.apply(10));
}
} | 25Y combinator
| 9java
| 6u3z |
from logpy import *
from logpy.core import lall
import time
def lefto(q, p, list):
return membero((q,p), zip(list, list[1:]))
def nexto(q, p, list):
return conde([lefto(q, p, list)], [lefto(p, q, list)])
houses = var()
zebraRules = lall(
(eq, (var(), var(), var(), var(), var()), houses),
(membero, ('Englishman', var(), var(), var(), 'red'), houses),
(membero, ('Swede', var(), var(), 'dog', var()), houses),
(membero, ('Dane', var(), 'tea', var(), var()), houses),
(lefto, (var(), var(), var(), var(), 'green'),
(var(), var(), var(), var(), 'white'), houses),
(membero, (var(), var(), 'coffee', var(), 'green'), houses),
(membero, (var(), 'Pall Mall', var(), 'birds', var()), houses),
(membero, (var(), 'Dunhill', var(), var(), 'yellow'), houses),
(eq, (var(), var(), (var(), var(), 'milk', var(), var()), var(), var()), houses),
(eq, (('Norwegian', var(), var(), var(), var()), var(), var(), var(), var()), houses),
(nexto, (var(), 'Blend', var(), var(), var()),
(var(), var(), var(), 'cats', var()), houses),
(nexto, (var(), 'Dunhill', var(), var(), var()),
(var(), var(), var(), 'horse', var()), houses),
(membero, (var(), 'Blue Master', 'beer', var(), var()), houses),
(membero, ('German', 'Prince', var(), var(), var()), houses),
(nexto, ('Norwegian', var(), var(), var(), var()),
(var(), var(), var(), var(), 'blue'), houses),
(nexto, (var(), 'Blend', var(), var(), var()),
(var(), var(), 'water', var(), var()), houses),
(membero, (var(), var(), var(), 'zebra', var()), houses)
)
t0 = time.time()
solutions = run(0, houses, zebraRules)
t1 = time.time()
dur = t1-t0
count = len(solutions)
zebraOwner = [house for house in solutions[0] if 'zebra' in house][0][0]
print % (count, dur)
print % zebraOwner
print
for line in solutions[0]:
print str(line) | 24Zebra puzzle
| 3python
| vk29 |
plot.yin.yang <- function(x=5, y=5, r=3, s=10, add=F){
suppressMessages(require("plotrix"))
if(!add) plot(1:10, type="n", xlim=c(0,s), ylim=c(0,s), xlab="", ylab="", xaxt="n", yaxt="n", bty="n", asp=1)
draw.circle(x, y, r, border="white", col= "black")
draw.ellipse(x, y, r, r, col="white", angle=0, segment=c(90,270), arc.only=F)
draw.ellipse(x, y - r * 0.5, r * 0.5, r * 0.5, col="black", border="black", angle=0, segment=c(90,270), arc.only=F)
draw.circle(x, y - r * 0.5, r * 0.125, border="white", col= "white")
draw.circle(x, y + r * 0.5, r * 0.5, col="white", border="white")
draw.circle(x, y + r * 0.5, r * 0.125, border="black", lty=1, col= "black")
draw.circle(x, y, r, border="black")
}
png("yin_yang.png")
plot.yin.yang()
plot.yin.yang(1,7,1, add=T)
dev.off() | 26Yin and yang
| 13r
| 4b5y |
function Y(f) {
var g = f((function(h) {
return function() {
var g = f(h(h));
return g.apply(this, arguments);
}
})(function(h) {
return function() {
var g = f(h(h));
return g.apply(this, arguments);
}
}));
return g;
}
var fac = Y(function(f) {
return function (n) {
return n > 1 ? n * f(n - 1) : 1;
};
});
var fib = Y(function(f) {
return function(n) {
return n > 1 ? f(n - 1) + f(n - 2) : n;
};
}); | 25Y combinator
| 10javascript
| l7cf |
library(combinat)
col <- factor(c("Red","Green","White","Yellow","Blue"))
own <- factor(c("English","Swedish","Danish","German","Norwegian"))
pet <- factor(c("Dog","Birds","Cats","Horse","Zebra"))
drink <- factor(c("Coffee","Tea","Milk","Beer","Water"))
smoke <- factor(c("PallMall", "Blend", "Dunhill", "BlueMaster", "Prince"))
col_p <- permn(levels(col))
own_p <- permn(levels(own))
pet_p <- permn(levels(pet))
drink_p <- permn(levels(drink))
smoke_p <- permn(levels(smoke))
imright <- function(h1,h2){
return(h1-h2==1)
}
nextto <- function(h1,h2){
return(abs(h1-h2)==1)
}
house_with <- function(f,val){
return(which(levels(f)==val))
}
for (i in seq(length(col_p))){
col <- factor(col, levels=col_p[[i]])
if (imright(house_with(col,"Green"),house_with(col,"White"))) {
for (j in seq(length(own_p))){
own <- factor(own, levels=own_p[[j]])
if(house_with(own,"English") == house_with(col,"Red")){
if(house_with(own,"Norwegian") == 1){
if(nextto(house_with(own,"Norwegian"),house_with(col,"Blue"))){
for(k in seq(length(drink_p))){
drink <- factor(drink, levels=drink_p[[k]])
if(house_with(drink,"Coffee") == house_with(col,"Green")){
if(house_with(own,"Danish") == house_with(drink,"Tea")){
if(house_with(drink,"Milk") == 3){
for(l in seq(length(smoke_p))){
smoke <- factor(smoke, levels=smoke_p[[l]])
if(house_with(smoke,"Dunhill") == house_with(col,"Yellow")){
if(house_with(smoke,"BlueMaster") == house_with(drink,"Beer")){
if(house_with(own,"German") == house_with(smoke,"Prince")){
if(nextto(house_with(smoke,"Blend"),house_with(drink,"Water"))){
for(m in seq(length(pet_p))){
pet <- factor(pet, levels=pet_p[[m]])
if(house_with(own,"Swedish") == house_with(pet,"Dog")){
if(house_with(smoke,"PallMall") == house_with(pet,"Birds")){
if(nextto(house_with(smoke,"Blend"),house_with(pet,"Cats"))){
if(nextto(house_with(smoke,"Dunhill"),house_with(pet,"Horse"))){
res <- sapply(list(own,col,pet,smoke,drink),levels)
colnames(res) <- c("Nationality","Colour","Pet","Drink","Smoke")
print(res)
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
} | 24Zebra puzzle
| 13r
| 9rmg |
null | 27Zig-zag matrix
| 11kotlin
| 5hua |
local zigzag = {}
function zigzag.new(n)
local a = {}
local i | 27Zig-zag matrix
| 1lua
| 4k5c |
Shoes.app(:width => 470, :height => 380) do
PI = Shoes::TWO_PI/2
strokewidth 1
def yin_yang(x, y, radius)
fill black; stroke black
arc x, y, radius, radius, -PI/2, PI/2
fill white; stroke white
arc x, y, radius, radius, PI/2, -PI/2
oval x-radius/4, y-radius/2, radius/2-1
fill black; stroke black
oval x-radius/4, y, radius/2-1
oval x-radius/12, y-radius/4-radius/12, radius/6-1
fill white; stroke white
oval x-radius/12, y+radius/4-radius/12, radius/6-1
nofill
stroke black
oval x-radius/2, y-radius/2, radius
end
yin_yang 190, 190, 360
yin_yang 410, 90, 90
end | 26Yin and yang
| 14ruby
| kxhg |
CONTENT = { House: '',
Nationality: %i[English Swedish Danish Norwegian German],
Colour: %i[Red Green White Blue Yellow],
Pet: %i[Dog Birds Cats Horse Zebra],
Drink: %i[Tea Coffee Milk Beer Water],
Smoke: %i[PallMall Dunhill BlueMaster Prince Blend] }
def adjacent? (n,i,g,e)
(0..3).any?{|x| (n[x]==i and g[x+1]==e) or (n[x+1]==i and g[x]==e)}
end
def leftof? (n,i,g,e)
(0..3).any?{|x| n[x]==i and g[x+1]==e}
end
def coincident? (n,i,g,e)
n.each_index.any?{|x| n[x]==i and g[x]==e}
end
def solve_zebra_puzzle
CONTENT[:Nationality].permutation{|nation|
next unless nation.first == :Norwegian
CONTENT[:Colour].permutation{|colour|
next unless leftof?(colour, :Green, colour, :White)
next unless coincident?(nation, :English, colour, :Red)
next unless adjacent?(nation, :Norwegian, colour, :Blue)
CONTENT[:Pet].permutation{|pet|
next unless coincident?(nation, :Swedish, pet, :Dog)
CONTENT[:Drink].permutation{|drink|
next unless drink[2] == :Milk
next unless coincident?(nation, :Danish, drink, :Tea)
next unless coincident?(colour, :Green, drink, :Coffee)
CONTENT[:Smoke].permutation{|smoke|
next unless coincident?(smoke, :PallMall, pet, :Birds)
next unless coincident?(smoke, :Dunhill, colour, :Yellow)
next unless coincident?(smoke, :BlueMaster, drink, :Beer)
next unless coincident?(smoke, :Prince, nation, :German)
next unless adjacent?(smoke, :Blend, pet, :Cats)
next unless adjacent?(smoke, :Blend, drink, :Water)
next unless adjacent?(smoke, :Dunhill,pet, :Horse)
print_out(nation, colour, pet, drink, smoke)
} } } } }
end
def print_out (nation, colour, pet, drink, smoke)
width = CONTENT.map{|x| x.flatten.map{|y|y.size}.max}
fmt = width.map{|w| }.join()
national = nation[ pet.find_index(:Zebra) ]
puts ,
puts fmt % CONTENT.keys, fmt % width.map{|w| *w}
[nation,colour,pet,drink,smoke].transpose.each.with_index(1){|x,n| puts fmt % [n,*x]}
end
solve_zebra_puzzle | 24Zebra puzzle
| 14ruby
| 5puj |
use svg::node::element::Path;
fn main() {
let doc = svg::Document::new()
.add(yin_yang(15.0, 1.0).set("transform", "translate(20,20)"))
.add(yin_yang(6.0, 1.0).set("transform", "translate(50,11)"));
svg::save("yin_yang.svg", &doc).unwrap();
} | 26Yin and yang
| 15rust
| bqkx |
null | 25Y combinator
| 11kotlin
| d9nz |
object Einstein extends App {
val possibleMembers = for { | 24Zebra puzzle
| 16scala
| 7wr9 |
import scala.swing.Swing.pair2Dimension
import scala.swing.{ MainFrame, Panel }
import java.awt.{ Color, Graphics2D }
object YinYang extends scala.swing.SimpleSwingApplication {
var preferedSize = 500
def drawTaijitu(g: Graphics2D, size: Int) {
val sizeMinsOne = size - 1 | 26Yin and yang
| 16scala
| a81n |
Y = function (f)
return function(...)
return (function(x) return x(x) end)(function(x) return f(function(y) return x(x)(y) end) end)(...)
end
end | 25Y combinator
| 1lua
| fcdp |
l = {}
l[1] = 1 | 13Arrays
| 1lua
| xvwz |
sub Y { my $f = shift;
sub { my $x = shift; $x->($x) }->(
sub {my $y = shift; $f->(sub {$y->($y)(@_)})}
)
}
my $fac = sub {my $f = shift;
sub {my $n = shift; $n < 2 ? 1 : $n * $f->($n-1)}
};
my $fib = sub {my $f = shift;
sub {my $n = shift; $n == 0 ? 0 : $n == 1 ? 1 : $f->($n-1) + $f->($n-2)}
};
for my $f ($fac, $fib) {
print join(' ', map Y($f)->($_), 0..9), "\n";
} | 25Y combinator
| 2perl
| jw7f |
<?php
function Y($f) {
$g = function($w) use($f) {
return $f(function() use($w) {
return call_user_func_array($w($w), func_get_args());
});
};
return $g($g);
}
$fibonacci = Y(function($f) {
return function($i) use($f) { return ($i <= 1)? $i : ($f($i-1) + $f($i-2)); };
});
echo $fibonacci(10), ;
$factorial = Y(function($f) {
return function($i) use($f) { return ($i <= 1)? 1 : ($f($i - 1) * $i); };
});
echo $factorial(10), ;
?> | 25Y combinator
| 12php
| tlf1 |
use 5.010;
sub zig_zag {
my $n = shift;
my $max_number = $n**2;
my @matrix;
my $number = 0;
for my $j ( 0 .. --$n ) {
for my $i (
$j % 2
? 0 .. $j
: reverse 0 .. $j
)
{
$matrix[$i][ $j - $i ] = $number++;
$matrix[ $n - $i ][ $n - ( $j - $i ) ] = $max_number - $number;
}
}
return @matrix;
}
my @zig_zag_matrix = zig_zag(5);
say join "\t", @{$_} foreach @zig_zag_matrix; | 27Zig-zag matrix
| 2perl
| oz8x |
function ZigZagMatrix($num) {
$matrix = array();
for ($i = 0; $i < $num; $i++){
$matrix[$i] = array();
}
$i=1;
$j=1;
for ($e = 0; $e < $num*$num; $e++) {
$matrix[$i-1][$j-1] = $e;
if (($i + $j) % 2 == 0) {
if ($j < $num){
$j++;
}else{
$i += 2;
}
if ($i > 1){
$i --;
}
} else {
if ($i < $num){
$i++;
}else{
$j += 2;
}
if ($j > 1){
$j --;
}
}
}
return $matrix;
} | 27Zig-zag matrix
| 12php
| gb42 |
>>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))
>>> fac = lambda f: lambda n: (1 if n<2 else n*f(n-1))
>>> [ Y(fac)(i) for i in range(10) ]
[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
>>> fib = lambda f: lambda n: 0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2))
>>> [ Y(fib)(i) for i in range(10) ]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34] | 25Y combinator
| 3python
| hxjw |
Y <- function(f) {
(function(x) { (x)(x) })( function(y) { f( (function(a) {y(y)})(a) ) } )
} | 25Y combinator
| 13r
| g147 |
def zigzag(n):
'''zigzag rows'''
def compare(xy):
x, y = xy
return (x + y, -y if (x + y)% 2 else y)
xs = range(n)
return {index: n for n, index in enumerate(sorted(
((x, y) for x in xs for y in xs),
key=compare
))}
def printzz(myarray):
'''show zigzag rows as lines'''
n = int(len(myarray) ** 0.5 + 0.5)
xs = range(n)
print('\n'.join(
[''.join(% myarray[(x, y)] for x in xs) for y in xs]
))
printzz(zigzag(6)) | 27Zig-zag matrix
| 3python
| i3of |
y = lambda do |f|
lambda {|g| g[g]}[lambda do |g|
f[lambda {|*args| g[g][*args]}]
end]
end
fac = lambda{|f| lambda{|n| n < 2? 1: n * f[n-1]}}
p Array.new(10) {|i| y[fac][i]}
fib = lambda{|f| lambda{|n| n < 2? n: f[n-1] + f[n-2]}}
p Array.new(10) {|i| y[fib][i]} | 25Y combinator
| 14ruby
| bskq |
zigzag1 <- function(n) {
j <- seq(n)
u <- rep(c(-1, 1), n)
v <- j * (2 * j - 1) - 1
v <- as.vector(rbind(v, v + 1))
a <- matrix(0, n, n)
for (i in seq(n)) {
a[i, ] <- v[j + i - 1]
v <- v + u
}
a
}
zigzag1(5) | 27Zig-zag matrix
| 13r
| sdqy |
null | 25Y combinator
| 15rust
| p0bu |
def Y[A, B](f: (A => B) => (A => B)): A => B = {
case class W(wf: W => (A => B)) {
def apply(w: W): A => B = wf(w)
}
val g: W => (A => B) = w => f(w(w))(_)
g(W(g))
} | 25Y combinator
| 16scala
| eiab |
def zigzag(n)
(seq=*0...n).product(seq)
.sort_by {|x,y| [x+y, (x+y).even?? y: -y]}
.each_with_index.sort.map(&:last).each_slice(n).to_a
end
def print_matrix(m)
format = * m[0].size
puts m.map {|row| format % row}
end
print_matrix zigzag(5) | 27Zig-zag matrix
| 14ruby
| dyns |
package main
import "fmt"
func main() {
doors := [100]bool{} | 21100 doors
| 0go
| gx4n |
use std::cmp::Ordering;
use std::cmp::Ordering::{Equal, Greater, Less};
use std::iter::repeat;
#[derive(Debug, PartialEq, Eq)]
struct SortIndex {
x: usize,
y: usize,
}
impl SortIndex {
fn new(x: usize, y: usize) -> SortIndex {
SortIndex { x, y }
}
}
impl PartialOrd for SortIndex {
fn partial_cmp(&self, other: &SortIndex) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for SortIndex {
fn cmp(&self, other: &SortIndex) -> Ordering {
let lower = if self.x + self.y == other.x + other.y {
if (self.x + self.y)% 2 == 0 {
self.x < other.x
} else {
self.y < other.y
}
} else {
(self.x + self.y) < (other.x + other.y)
};
if lower {
Less
} else if self == other {
Equal
} else {
Greater
}
}
}
fn zigzag(n: usize) -> Vec<Vec<usize>> {
let mut l: Vec<SortIndex> = (0..n * n).map(|i| SortIndex::new(i% n, i / n)).collect();
l.sort();
let init_vec = vec![0; n];
let mut result: Vec<Vec<usize>> = repeat(init_vec).take(n).collect();
for (i, &SortIndex { x, y }) in l.iter().enumerate() {
result[y][x] = i
}
result
}
fn main() {
println!("{:?}", zigzag(5));
} | 27Zig-zag matrix
| 15rust
| fmd6 |
def zigzag(n: Int): Array[Array[Int]] = {
val l = for (i <- 0 until n*n) yield (i%n, i/n)
val lSorted = l.sortWith {
case ((x,y), (u,v)) =>
if (x+y == u+v)
if ((x+y) % 2 == 0) x<u else y<v
else x+y < u+v
}
val res = Array.ofDim[Int](n, n)
lSorted.zipWithIndex foreach {
case ((x,y), i) => res(y)(x) = i
}
res
}
zigzag(5).foreach{
ar => ar.foreach(x => print("%3d".format(x)))
println
} | 27Zig-zag matrix
| 16scala
| 3lzy |
doors = [false] * 100
(0..99).each {
it.step(100, it + 1) {
doors[it] ^= true
}
}
(0..99).each {
println("Door #${it + 1} is ${doors[it]? 'open': 'closed'}.")
} | 21100 doors
| 7groovy
| 2plv |
struct RecursiveFunc<F> {
let o: RecursiveFunc<F> -> F
}
func Y<A, B>(f: (A -> B) -> A -> B) -> A -> B {
let r = RecursiveFunc<A -> B> { w in f { w.o(w)($0) } }
return r.o(r)
}
let fac = Y { (f: Int -> Int) in
{ $0 <= 1? 1: $0 * f($0-1) }
}
let fib = Y { (f: Int -> Int) in
{ $0 <= 2? 1: f($0-1)+f($0-2) }
}
println("fac(5) = \(fac(5))")
println("fib(9) = \(fib(9))") | 25Y combinator
| 17swift
| kqhx |
data Door
= Open
| Closed
deriving (Eq, Show)
toggle :: Door -> Door
toggle Open = Closed
toggle Closed = Open
toggleEvery :: Int -> [Door] -> [Door]
toggleEvery k = zipWith toggleK [1 ..]
where
toggleK n door
| n `mod` k == 0 = toggle door
| otherwise = door
run :: Int -> [Door]
run n = foldr toggleEvery (replicate n Closed) [1 .. n]
main :: IO ()
main = print $ filter ((== Open) . snd) $ zip [1 ..] (run 100) | 21100 doors
| 8haskell
| syqk |
my @empty;
my @empty_too = ();
my @populated = ('This', 'That', 'And', 'The', 'Other');
print $populated[2];
my $aref = ['This', 'That', 'And', 'The', 'Other'];
print $aref->[2]; | 13Arrays
| 2perl
| lsc5 |
$NumberArray = array(0, 1, 2, 3, 4, 5, 6);
$LetterArray = array(, , , , , );
$simpleForm = ['apple', 'orange']; | 13Arrays
| 12php
| qux3 |
int main(int argC,char* argV[])
{
char str[1000];
if(argC!=5)
printf(,argV[0]);
else{
sprintf(str,%s\,argV[1],argV[2],argV[3],argV[4]);
system(str);
}
return 0;
} | 28Write to Windows event log
| 5c
| 3cza |
(use 'clojure.java.shell)
(sh "eventcreate" "/T" "INFORMATION" "/ID" "123" "/D" "Rosetta Code example") | 28Write to Windows event log
| 6clojure
| c59b |
package main
import (
"fmt"
"os/exec"
)
func main() {
command := "EventCreate"
args := []string{"/T", "INFORMATION", "/ID", "123", "/L", "APPLICATION",
"/SO", "Go", "/D", "\"Rosetta Code Example\""}
cmd := exec.Command(command, args...)
err := cmd.Run()
if err != nil {
fmt.Println(err)
}
} | 28Write to Windows event log
| 0go
| bwkh |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
public class WriteToWindowsEventLog {
public static void main(String[] args) throws IOException, InterruptedException {
String osName = System.getProperty("os.name").toUpperCase(Locale.ENGLISH);
if (!osName.startsWith("WINDOWS")) {
System.err.println("Not windows");
return;
}
Process process = Runtime.getRuntime().exec("EventCreate /t INFORMATION /id 123 /l APPLICATION /so Java /d \"Rosetta Code Example\"");
process.waitFor(10, TimeUnit.SECONDS);
int exitValue = process.exitValue();
System.out.printf("Process exited with value%d\n", exitValue);
if (exitValue != 0) {
InputStream errorStream = process.getErrorStream();
String result = new BufferedReader(new InputStreamReader(errorStream))
.lines()
.collect(Collectors.joining("\n"));
System.err.println(result);
}
}
} | 28Write to Windows event log
| 9java
| snq0 |
array = []
array.append(1)
array.append(3)
array[0] = 2
print array[0] | 13Arrays
| 3python
| 20lz |
null | 28Write to Windows event log
| 11kotlin
| as13 |
class HundredDoors {
public static void main(String[] args) {
boolean[] doors = new boolean[101];
for (int i = 1; i < doors.length; i++) {
for (int j = i; j < doors.length; j += i) {
doors[j] = !doors[j];
}
}
for (int i = 1; i < doors.length; i++) {
if (doors[i]) {
System.out.printf("Door%d is open.%n", i);
}
}
}
} | 21100 doors
| 9java
| 1dp2 |
use strict;
use warnings;
use Win32::EventLog;
my $handle = Win32::EventLog->new("Application");
my $event = {
Computer => $ENV{COMPUTERNAME},
Source => 'Rosettacode',
EventType => EVENTLOG_INFORMATION_TYPE,
Category => 'test',
EventID => 0,
Data => 'a test for rosettacode',
Strings => 'a string test for rosettacode',
};
$handle->Report($event); | 28Write to Windows event log
| 2perl
| 9umn |
var doors=[];
for (var i=0;i<100;i++)
doors[i]=false;
for (var i=1;i<=100;i++)
for (var i2=i-1,g;i2<100;i2+=i)
doors[i2]=!doors[i2];
for (var i=1;i<=100;i++)
console.log("Door%d is%s",i,doors[i-1]?"open":"closed") | 21100 doors
| 10javascript
| q6x8 |
arr <- array(1)
arr <- append(arr,3)
arr[1] <- 2
print(arr[1]) | 13Arrays
| 13r
| mwy4 |
import win32api
import win32con
import win32evtlog
import win32security
import win32evtlogutil
ph = win32api.GetCurrentProcess()
th = win32security.OpenProcessToken(ph, win32con.TOKEN_READ)
my_sid = win32security.GetTokenInformation(th, win32security.TokenUser)[0]
applicationName =
eventID = 1
category = 5
myType = win32evtlog.EVENTLOG_WARNING_TYPE
descr = [, ]
data = .encode()
win32evtlogutil.ReportEvent(applicationName, eventID, eventCategory=category,
eventType=myType, strings=descr, data=data, sid=my_sid) | 28Write to Windows event log
| 3python
| c59q |
require 'win32/eventlog'
logger = Win32::EventLog.new
logger.report_event(:event_type => Win32::EventLog::INFO, :data => ) | 28Write to Windows event log
| 14ruby
| 2glw |
#[cfg(windows)]
mod bindings {
::windows::include_bindings!();
}
#[cfg(windows)]
use bindings::{
Windows::Win32::Security::{
GetTokenInformation, OpenProcessToken, PSID, TOKEN_ACCESS_MASK, TOKEN_INFORMATION_CLASS,
TOKEN_USER,
},
Windows::Win32::SystemServices::{
GetCurrentProcess, OpenEventLogA, ReportEventA, ReportEvent_wType, HANDLE, PSTR,
},
};
#[cfg(windows)]
fn main() -> windows::Result<()> {
let ph = unsafe { GetCurrentProcess() };
let mut th: HANDLE = HANDLE(0);
unsafe { OpenProcessToken(ph, TOKEN_ACCESS_MASK::TOKEN_QUERY, &mut th) }.ok()?; | 28Write to Windows event log
| 15rust
| vr2t |
object RegisterWinLogEvent extends App {
import sys.process._
def eventCreate= Seq("EVENTCREATE", "/T", "SUCCESS", "/id", "123", "/l", "APPLICATION", "/so", "Scala RegisterWinLogEvent", "/d", "Rosetta Code Example" ).!!
println(eventCreate)
println(s"\nSuccessfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart} ms]")
} | 28Write to Windows event log
| 16scala
| 4h50 |
fun oneHundredDoors(): List<Int> {
val doors = BooleanArray(100, { false })
for (i in 0..99) {
for (j in i..99 step (i + 1)) {
doors[j] = !doors[j]
}
}
return doors
.mapIndexed { i, b -> i to b }
.filter { it.second }
.map { it.first + 1 }
} | 21100 doors
| 11kotlin
| j07r |
int main(void)
{
return 0 >= fputs(,
freopen(,,stdout));
} | 29Write entire file
| 5c
| rkg7 |
(spit "file.txt" "this is a string") | 29Write entire file
| 6clojure
| bekz |
int main(int argc, char **argv) {
float x[4] = {1,2,3,1e11}, y[4];
int i = 0;
FILE *filePtr;
filePtr = fopen(,);
for (i = 0; i < 4; i++) {
y[i] = sqrt(x[i]);
fprintf(filePtr, , x[i], y[i]);
}
return 0;
} | 30Write float arrays to a text file
| 5c
| 8n04 |
int main()
{
xmlDoc *doc = xmlNewDoc();
xmlNode *root = xmlNewNode(NULL, BAD_CAST );
xmlDocSetRootElement(doc, root);
xmlNode *node = xmlNewNode(NULL, BAD_CAST );
xmlAddChild(node, xmlNewText(BAD_CAST ));
xmlAddChild(root, node);
xmlSaveFile(, doc);
xmlFreeDoc(doc);
xmlCleanupParser();
} | 31XML/DOM serialization
| 5c
| s8q5 |
(require '[clojure.data.xml:as xml])
(def xml-example (xml/element:root {} (xml/element:element {} "Some text here")))
(with-open [out-file (java.io.OutputStreamWriter.
(java.io.FileOutputStream. "/tmp/output.xml") "UTF-8")]
(xml/emit xml-example out-file)) | 31XML/DOM serialization
| 6clojure
| nfik |
import "io/ioutil"
func main() {
ioutil.WriteFile("path/to/your.file", []byte("data"), 0644)
} | 29Write entire file
| 0go
| nzi1 |
a = ['foo']
a << 1
a.push(3,4,5)
a[0] = 2
a[0,3] = 'bar'
a[1..-1] = 'baz'
a[0] = nil
a[0,1] = nil
puts a[0] | 13Arrays
| 14ruby
| uovz |
new File("myFile.txt").text = """a big string
that can be
splitted over lines
""" | 29Write entire file
| 7groovy
| siq1 |
main :: IO ( )
main = do
putStrLn "Enter a string!"
str <- getLine
putStrLn "Where do you want to store this string?"
myFile <- getLine
appendFile myFile str | 29Write entire file
| 8haskell
| urv2 |
import java.io.*;
public class Test {
public static void main(String[] args) throws IOException {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("test.txt"))) {
bw.write("abc");
}
}
} | 29Write entire file
| 9java
| m2ym |
let a = [1, 2, 3]; | 13Arrays
| 15rust
| 5iuq |
null | 29Write entire file
| 11kotlin
| tyf0 |
int compare(const void *a, const void *b) {
int int_a = *((int *)a);
int int_b = *((int *)b);
return (int_a > int_b) - (int_a < int_b);
}
char results[7];
bool next_result() {
char *ptr = results + 5;
int num = 0;
size_t i;
if (strcmp(results, ) == 0) {
return false;
}
for (i = 0; results[i] != 0; i++) {
int d = results[i] - '0';
num = 3 * num + d;
}
num++;
while (num > 0) {
int rem = num % 3;
num /= 3;
*ptr-- = rem + '0';
}
while (ptr > results) {
*ptr-- = '0';
}
return true;
}
char *games[6] = { , , , , , };
char *places[4] = { , , , };
int main() {
int points[4][10];
size_t i, j;
strcpy(results, );
for (i = 0; i < 4; i++) {
for (j = 0; j < 10; j++) {
points[i][j] = 0;
}
}
do {
int records[] = { 0, 0, 0, 0 };
for (i = 0; i < 6; i++) {
switch (results[i]) {
case '2':
records[games[i][0] - '1'] += 3;
break;
case '1':
records[games[i][0] - '1']++;
records[games[i][1] - '1']++;
break;
case '0':
records[games[i][1] - '1'] += 3;
break;
default:
break;
}
}
qsort(records, 4, sizeof(int), compare);
for (i = 0; i < 4; i++) {
points[i][records[i]]++;
}
} while (next_result());
printf();
printf();
for (i = 0; i < 4; i++) {
printf(, places[i]);
for (j = 0; j < 10; j++) {
printf(, points[3 - i][j]);
}
printf();
}
return 0;
} | 32World Cup group stage
| 5c
| oi80 |
package main
import (
"fmt"
dom "gitlab.com/stone.code/xmldom-go.git"
)
func main() {
d, err := dom.ParseStringXml(`
<?xml version="1.0"?>
<root>
<element>
Some text here
</element>
</root>`)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(d.ToXml()))
} | 31XML/DOM serialization
| 0go
| v52m |
function writeFile (filename, data)
local f = io.open(filename, 'w')
f:write(data)
f:close()
end
writeFile("stringFile.txt", "Mmm... stringy.") | 29Write entire file
| 1lua
| zmty |
null | 13Arrays
| 16scala
| rfgn |
import groovy.xml.MarkupBuilder
def writer = new StringWriter() << '<?xml version="1.0"?>\n'
def xml = new MarkupBuilder(writer)
xml.root() {
element('Some text here' )
}
println writer | 31XML/DOM serialization
| 7groovy
| mcy5 |
import Data.List
import Text.XML.Light
xmlDOM :: String -> String
xmlDOM txt = showTopElement $ Element
(unqual "root")
[]
[ Elem $ Element
(unqual "element")
[]
[Text $ CData CDataText txt Nothing]
Nothing
]
Nothing | 31XML/DOM serialization
| 8haskell
| exai |
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class RDOMSerialization {
private Document domDoc;
public RDOMSerialization() {
return;
}
protected void buildDOMDocument() {
DocumentBuilderFactory factory;
DocumentBuilder builder;
DOMImplementation impl;
Element elmt1;
Element elmt2;
try {
factory = DocumentBuilderFactory.newInstance();
builder = factory.newDocumentBuilder();
impl = builder.getDOMImplementation();
domDoc = impl.createDocument(null, null, null);
elmt1 = domDoc.createElement("root");
elmt2 = domDoc.createElement("element");
elmt2.setTextContent("Some text here");
domDoc.appendChild(elmt1);
elmt1.appendChild(elmt2);
}
catch (ParserConfigurationException ex) {
ex.printStackTrace();
}
return;
}
protected void serializeXML() {
DOMSource domSrc;
Transformer txformer;
StringWriter sw;
StreamResult sr;
try {
domSrc = new DOMSource(domDoc);
txformer = TransformerFactory.newInstance().newTransformer();
txformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
txformer.setOutputProperty(OutputKeys.METHOD, "xml");
txformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
txformer.setOutputProperty(OutputKeys.INDENT, "yes");
txformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
txformer.setOutputProperty("{http: | 31XML/DOM serialization
| 9java
| hbjm |
use File::Slurper 'write_text';
write_text($filename, $data); | 29Write entire file
| 2perl
| kahc |
local is_open = {}
for pass = 1,100 do
for door = pass,100,pass do
is_open[door] = not is_open[door]
end
end
for i,v in next,is_open do
print ('Door '..i..':',v and 'open' or 'close')
end | 21100 doors
| 1lua
| h8j8 |
var doc = document.implementation.createDocument( null, 'root', null );
var root = doc.documentElement;
var element = doc.createElement( 'element' );
root.appendChild( element );
element.appendChild( document.createTextNode('Some text here') );
var xmlString = new XMLSerializer().serializeToString( doc ); | 31XML/DOM serialization
| 10javascript
| aw10 |
file_put_contents($filename, $data) | 29Write entire file
| 12php
| 39zq |
null | 31XML/DOM serialization
| 11kotlin
| 4r57 |
package main
import (
"fmt"
"os"
)
var (
x = []float64{1, 2, 3, 1e11}
y = []float64{1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}
xprecision = 3
yprecision = 5
)
func main() {
if len(x) != len(y) {
fmt.Println("x, y different length")
return
}
f, err := os.Create("filename")
if err != nil {
fmt.Println(err)
return
}
for i := range x {
fmt.Fprintf(f, "%.*e,%.*e\n", xprecision-1, x[i], yprecision-1, y[i])
}
f.Close()
} | 30Write float arrays to a text file
| 0go
| 5rul |
with open(filename, 'w') as f:
f.write(data) | 29Write entire file
| 3python
| bekr |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.