code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
use strict; use warnings; my ($w, $h) = (9, 9); my @v = map([ (0) x ($w + 1) ], 0 .. $h); my @f = map([ (0) x ($w + 1) ], 0 .. $h); my @d = map([ (0) x ($w + 1) ], 0 .. $h); my @n; for my $i (0 .. $h) { push @{$n[$i][$_]}, [$i, $_ - 1] for 1 .. $w; push @{$n[$i][$_]}, [$i, $_ + 1] for 0 .. $w - 1; } for my $j (...
347Resistor mesh
2perl
vfu20
public class ReflectionGetSource { public static void main(String[] args) { new ReflectionGetSource().method1(); } public ReflectionGetSource() {} public void method1() { method2(); } public void method2() { method3(); } public void method3() { Throw...
351Reflection/Get source
9java
jm47c
function foo() {...} foo.toString();
351Reflection/Get source
10javascript
1vhp7
(defn repeat-function [f n] (dotimes [i n] (f)))
352Repeat
6clojure
co39b
int main() { rename(, ); rename(, ); rename(, ); rename(, ); return 0; }
353Rename a file
5c
r62g7
romanToArabic <- function(roman) { romanLookup <- c(I=1L, V=5L, X=10L, L=50L, C=100L, D=500L, M=1000L) rSplit <- strsplit(toupper(roman), character(0)) toArabic <- function(item) { digits <- romanLookup[item] if (length(digits) > 1L) { smaller <- (digits[-length(digits)] < digits[-1L]) digits...
340Roman numerals/Decode
13r
ryagj
package main import ( "fmt" "image" "reflect" )
354Reflection/List properties
0go
5tmul
import java.lang.reflect.Field @SuppressWarnings("unused") class ListProperties { public int examplePublicField = 42 private boolean examplePrivateField = true static void main(String[] args) { ListProperties obj = new ListProperties() Class clazz = obj.class println "All public f...
354Reflection/List properties
7groovy
cot9i
null
351Reflection/Get source
11kotlin
5tlua
debug = require("debug") function foo(bar) info = debug.getinfo(1) for k,v in pairs(info) do print(k,v) end end foo()
351Reflection/Get source
1lua
4z25c
from __future__ import annotations import asyncio import sys from typing import Optional from typing import TextIO class OutOfInkError(Exception): class Printer: def __init__(self, name: str, backup: Optional[Printer]): self.name = name self.backup = backup self.ink_level: int = ...
350Rendezvous
3python
jmg7p
DIFF_THRESHOLD = 1e-40 class Fixed: FREE = 0 A = 1 B = 2 class Node: __slots__ = [, ] def __init__(self, v=0.0, f=Fixed.FREE): self.voltage = v self.fixed = f def set_boundary(m): m[1][1] = Node( 1.0, Fixed.A) m[6][7] = Node(-1.0, Fixed.B) def calc_difference(m, d): h...
347Resistor mesh
3python
ut5vd
my @symbols = ( [1000, 'M'], [900, 'CM'], [500, 'D'], [400, 'CD'], [100, 'C'], [90, 'XC'], [50, 'L'], [40, 'XL'], [10, 'X'], [9, 'IX'], [5, 'V'], [4, 'IV'], [1, 'I'] ); sub roman { my($n, $r) = (shift, ''); ($r, $n) = ('-', -$n) if $n < 0; foreach my $s (@symbols) { my($arabic, $roman) = @$s; ($r, $n)...
341Roman numerals/Encode
2perl
43b5d
=> (keys (ns-interns 'clojure.set)) (union map-invert join select intersection superset? index bubble-max-key subset? rename rename-keys project difference) => (keys (ns-publics 'clojure.set)) (union map-invert join select intersection superset? index subset? rename rename-keys project difference)
355Reflection/List methods
6clojure
npwik
import java.lang.reflect.Field; public class ListFields { public int examplePublicField = 42; private boolean examplePrivateField = true; public static void main(String[] args) throws IllegalAccessException { ListFields obj = new ListFields(); Class clazz = obj.getClass(); System....
354Reflection/List properties
9java
bl4k3
use strict; use warnings; use Class::Inspector; print Class::Inspector->resolved_filename( 'IO::Socket::INET' ), "\n";
351Reflection/Get source
2perl
okq8x
import os os.__file__
351Reflection/Get source
3python
ibsof
(import '(java.io File)) (.renameTo (File. "input.txt") (File. "output.txt")) (.renameTo (File. "docs") (File. "mydocs")) (.renameTo (File. (str (File/separator) "input.txt")) (File. (str (File/separator) "output.txt"))) (.renameTo (File. (str (File/separator) "docs")) (File. (str (File/separator) "mydocs")))
353Rename a file
6clojure
blgkz
var obj = Object.create({ name: 'proto', proto: true, doNothing: function() {} }, { name: {value: 'obj', writable: true, configurable: true, enumerable: true}, obj: {value: true, writable: true, configurable: true, enumerable: true}, 'non-enum': {value: 'non-enumerable', writable: true, enumer...
354Reflection/List properties
10javascript
w4he2
require 'mathn' Math.method(:sqrt).source_location Class.method(:nesting).source_location
351Reflection/Get source
14ruby
d18ns
int main() { regex_t preg; regmatch_t substmatch[1]; const char *tp = ; const char *t1 = ; const char *t2 = ; const char *ss = ; regcomp(&preg, , REG_EXTENDED); printf(, t1, (regexec(&preg, t1, 0, NULL, 0)==0) ? : , tp); printf(, t2, ...
356Regular expressions
5c
ok180
void * record(size_t bytes) { int fd; if (-1 == (fd = open(, O_RDONLY))) return 0; void *a = malloc(bytes); read(fd, a, bytes); close(fd); return a; } int play(void *buf, size_t len) { int fd; if (-1 == (fd = open(, O_WRONLY))) return 0; write(fd, buf, len); close(fd); return 1; } int main() { void *p = r...
357Record sound
5c
1v5pj
package main import ( "fmt" "image" "reflect" ) type t int
355Reflection/List methods
0go
vd32m
null
354Reflection/List properties
11kotlin
r6lgo
int repstr(char *str) { if (!str) return 0; size_t sl = strlen(str) / 2; while (sl > 0) { if (strstr(str, str + sl) == str) return sl; --sl; } return 0; } int main(void) { char *strs[] = { , , , , , , , , , }; size_t strslen = sizeof(strs) / sizeof(st...
358Rep-string
5c
tewf4
function int2roman($number) { if (!is_int($number) || $number < 1) return false; $integers = array(900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1); $numerals = array('CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'); $major = intval($number / 1000) * 1000; $minor = $number - $maj...
341Roman numerals/Encode
12php
ip6ov
import java.lang.reflect.Method; public class ListMethods { public int examplePublicInstanceMethod(char c, double d) { return 42; } private boolean examplePrivateInstanceMethod(String s) { return true; } public static void main(String[] args) { Class clazz = ListMethods.cl...
355Reflection/List methods
9java
h9vjm
a = 1 b = 2.0 c = "hello world" function listProperties(t) if type(t) == "table" then for k,v in pairs(t) do if type(v) ~= "function" then print(string.format("%7s:%s", type(v), k)) end end end end print("Global properties") listProperties(_G) print("Pac...
354Reflection/List properties
1lua
7y2ru
null
355Reflection/List methods
10javascript
aur10
(defn rep-string [s] (let [len (count s) first-half (subs s 0 (/ len 2)) test-group (take-while seq (iterate butlast first-half)) test-reptd (map (comp #(take len %) cycle) test-group)] (some #(= (seq s) %) test-reptd)))
358Rep-string
6clojure
m08yq
(let [s "I am a string"] (when (re-find #"string$" s) (println "Ends with 'string'.")) (when-not (re-find #"^You" s) (println "Does not start with 'You'.")) (println (clojure.string/replace s " a " " another ")) )
356Regular expressions
6clojure
teqfv
def fromRoman(roman) r = roman.upcase n = 0 until r.empty? do case when r.start_with?('M') then v = 1000; len = 1 when r.start_with?('CM') then v = 900; len = 2 when r.start_with?('D') then v = 500; len = 1 when r.start_with?('CD') then v = 400; len = 2 when r.start_with?('C') then v...
340Roman numerals/Decode
14ruby
pv0bh
package main import ( "bufio" "fmt" "log" "os" "os/exec" "strconv" ) func check(err error) { if err != nil { log.Fatal(err) } } func main() { scanner := bufio.NewScanner(os.Stdin) name := "" for name == "" { fmt.Print("Enter output file name (without extens...
357Record sound
0go
ys864
null
355Reflection/List methods
11kotlin
4zm57
{ package Point; use Class::Spiffy -base; field 'x'; field 'y'; } { package Circle; use base qw(Point); field 'r'; } my $p1 = Point->new(x => 8, y => -5); my $c1 = Circle->new(r => 4); my $c2 = Circle->new(x => 1, y => 2, r => 3); use Data::Dumper; say Dumper $p1; say Dumper $c1; ...
354Reflection/List properties
2perl
d1qnw
RegExp regexp = new RegExp(r'\w+\!'); String capitalize(Match m) => '${m[0].substring(0, m[0].length-1).toUpperCase()}'; void main(){ String hello = 'hello hello! world world!'; String hellomodified = hello.replaceAllMapped(regexp, capitalize); print(hello); print(hellomodified); }
356Regular expressions
18dart
w47eo
package main import "fmt" func repeat(n int, f func()) { for i := 0; i < n; i++ { f() } } func fn() { fmt.Println("Example") } func main() { repeat(4, fn) }
352Repeat
0go
blrkh
import Control.Monad (replicateM_) sampleFunction :: IO () sampleFunction = putStrLn "a" main = replicateM_ 5 sampleFunction
352Repeat
8haskell
d10n4
null
357Record sound
11kotlin
con98
function helloWorld() print "Hello World" end
355Reflection/List methods
1lua
g394j
<? class Foo { } $obj = new Foo(); $obj->bar = 42; $obj->baz = true; var_dump(get_object_vars($obj)); ?>
354Reflection/List properties
12php
jmv7z
struct RomanNumeral { symbol: &'static str, value: u32 } const NUMERALS: [RomanNumeral; 13] = [ RomanNumeral {symbol: "M", value: 1000}, RomanNumeral {symbol: "CM", value: 900}, RomanNumeral {symbol: "D", value: 500}, RomanNumeral {symbol: "CD", value: 400}, RomanNumeral {symbol: "C", va...
340Roman numerals/Decode
15rust
1u8pu
char * string_repeat( int n, const char * s ) { size_t slen = strlen(s); char * dest = malloc(n*slen+1); int i; char * p; for ( i=0, p = dest; i < n; ++i, p += slen ) { memcpy(p, s, slen); } *p = '\0'; return dest; } int main() { char * result = string_repeat(5, ); puts(result); free(result); ...
359Repeat a string
5c
2nnlo
import java.util.function.Consumer; import java.util.stream.IntStream; public class Repeat { public static void main(String[] args) { repeat(3, (x) -> System.out.println("Example " + x)); } static void repeat (int n, Consumer<Integer> fun) { IntStream.range(0, n).forEach(i -> fun.accept(i...
352Repeat
9java
s7aq0
>>> u'foo'.encode('rot13') 'sbb' >>> 'sbb'.decode('rot13') u'foo'
338Rot-13
3python
rywgq
def fromRoman( r:String ) : Int = { val arabicNumerals = List("CM"->900,"M"->1000,"CD"->400,"D"->500,"XC"->90,"C"->100, "XL"->40,"L"->50,"IX"->9,"X"->10,"IV"->4,"V"->5,"I"->1) var s = r arabicNumerals.foldLeft(0){ (n,t) => { val l = s.length; s = s.repl...
340Roman numerals/Decode
16scala
wgnes
int main(int argc, char **argv) { FILE *fp; char *buf; size_t sz; int start, count, lines = 1; int dest = 0, src = 0, pos = -1; if (argc != 4) ERROR(, argv[0]); if ((count = atoi(argv[3])) < 1) return 0; if ((start = atoi(argv[2])) < 1) ERROR(, start); ...
360Remove lines from a file
5c
p2lby
package Nums; use overload ('<=>' => \&compare); sub new { my $self = shift; bless [@_] } sub flip { my @a = @_; 1/$a } sub double { my @a = @_; 2*$a } sub compare { my ($a, $b) = @_; abs($a) <=> abs($b) } my $a = Nums->new(42); print "$_\n" for %{ref ($a)."::" });
355Reflection/List methods
2perl
ibeo3
class Parent(object): __priv = 'private' def __init__(self, name): self.name = name def __repr__(self): return '%s(%s)'% (type(self).__name__, self.name) def doNothing(self): pass import re class Child(Parent): __rePrivate = re.compile('^_(Child|Parent)__') ...
354Reflection/List properties
3python
fasde
null
352Repeat
11kotlin
auh13
package main import "os" func main() { os.Rename("input.txt", "output.txt") os.Rename("docs", "mydocs") os.Rename("/input.txt", "/output.txt") os.Rename("/docs", "/mydocs") }
353Rename a file
0go
npqi1
['input.txt':'output.txt', 'docs':'mydocs'].each { src, dst -> ['.', ''].each { dir -> new File("$dir/$src").renameTo(new File("$dir/$dst")) } }
353Rename a file
7groovy
s71q1
package main import ( "fmt" "strings" )
349Reverse words in a string
0go
ok08q
import pyaudio chunk = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 44100 p = pyaudio.PyAudio() stream = p.open(format = FORMAT, channels = CHANNELS, rate = RATE, input = True, frames_per_buffer = chunk) data = stream.read(chunk) print [ord(i) for...
357Record sound
3python
qrjxi
<? class Foo { function bar(int $x) { } } $method_names = get_class_methods('Foo'); foreach ($method_names as $name) { echo ; $method_info = new ReflectionMethod('Foo', $name); echo $method_info; } ?>
355Reflection/List methods
12php
r6cge
class Foo @@xyz = nil def initialize(name, age) @name, @age = name, age end def add_sex(sex) @sex = sex end end p foo = Foo.new(, 18) p foo.instance_variables p foo.instance_variable_defined?(:@age) p foo.instance_variable_get(:@age) p foo.instance_variable_set(:@ag...
354Reflection/List properties
14ruby
zw8tw
import System.IO import System.Directory main = do renameFile "input.txt" "output.txt" renameDirectory "docs" "mydocs" renameFile "/input.txt" "/output.txt" renameDirectory "/docs" "/mydocs"
353Rename a file
8haskell
ufmv2
def text = new StringBuilder() .append('---------- Ice and Fire ------------\n') .append(' \n') .append('fire, in end will world the say Some\n') .append('ice. in say Some \n') .append('desire of tasted I\'ve what From \n') .append('fire....
349Reverse words in a string
7groovy
xgewl
typedef int bool; int main() { int i, n, k = 0, next, *a; bool foundDup = FALSE; gboolean alreadyUsed; GHashTable* used = g_hash_table_new(g_direct_hash, g_direct_equal); GHashTable* used1000 = g_hash_table_new(g_direct_hash, g_direct_equal); a = malloc(400000 * sizeof(int)); a[0] = 0; ...
361Recaman's sequence
5c
w4uec
import java.io.{File, IOException} import javax.sound.sampled.{AudioFileFormat, AudioFormat, AudioInputStream} import javax.sound.sampled.{AudioSystem, DataLine, LineUnavailableException, TargetDataLine} object SoundRecorder extends App {
357Record sound
16scala
npaic
import inspect class Super(object): def __init__(self, name): self.name = name def __str__(self): return % (self.name,) def doSup(self): return 'did super stuff' @classmethod def cls(cls): return 'cls method (in sup)' @classmethod def supCls(cls): return 'Super method' @static...
355Reflection/List methods
3python
npwiz
object ListProperties extends App { private val obj = new { val examplePublicField: Int = 42 private val examplePrivateField: Boolean = true } private val clazz = obj.getClass println("All public methods (including inherited):") clazz.getFields.foreach(f => println(s"${f}\t${f.get(obj)}")) println...
354Reflection/List properties
16scala
m0dyc
function myFunc () print("Sure looks like a function in here...") end function rep (func, times) for count = 1, times do func() end end rep(myFunc, 4)
352Repeat
1lua
e5kac
revstr :: String -> String revstr = unwords . reverse . words revtext :: String -> String revtext = unlines . map revstr . lines test = revtext " \\n\ \fire, in end will world the say Some\n\ \ice. in say Some\n\ \desire of tasted I've what From\n\ \fire. favor who those wi...
349Reverse words in a string
8haskell
2ncll
rot13 <- function(x) { old <- paste(letters, LETTERS, collapse="", sep="") new <- paste(substr(old, 27, 52), substr(old, 1, 26), sep="") chartr(old, new, x) } x <- "The Quick Brown Fox Jumps Over The Lazy Dog!.,:;' rot13(x) x2 <- paste(letters, LETTERS, collapse="", sep="") rot13(x2)
338Rot-13
13r
utpvx
(apply str (repeat 5 "ha"))
359Repeat a string
6clojure
g334f
(require '[clojure.java.io:as jio] '[clojure.string:as str]) (defn remove-lines1 [filepath start nskip] (let [lines (str/split-lines (slurp filepath)) new-lines (concat (take (dec start) lines) (drop (+ (dec start) nskip) lines)) diff (- (count lines) (count new-lin...
360Remove lines from a file
6clojure
xg4wk
func addsub(x, y int) (int, int) { return x + y, x - y }
348Return multiple values
0go
a5a1f
def addSub(x,y) { [ sum: x+y, difference: x-y ] }
348Return multiple values
7groovy
hchj9
class Super CLASSNAME = 'super' def initialize(name) @name = name def self.superOwn 'super owned' end end def to_s end def doSup 'did super stuff' end def self.superClassStuff 'did super class stuff' end protected def protSup end private def privSup ...
355Reflection/List methods
14ruby
faqdr
import java.io.File; public class FileRenameTest { public static boolean renameFile(String oldname, String newname) {
353Rename a file
9java
m0fym
public class ReverseWords { static final String[] lines = { " ----------- Ice and Fire ----------- ", " ", " fire, in end will world the say Some ", " ice. in say Some ", " desire of tasted I've what From ", ...
349Reverse words in a string
9java
6qz3z
addsub x y = (x + y, x - y)
348Return multiple values
8haskell
zxzt0
object ListMethods extends App { private val obj = new { def examplePublicInstanceMethod(c: Char, d: Double) = 42 private def examplePrivateInstanceMethod(s: String) = true } private val clazz = obj.getClass println("All public methods (including inherited):") clazz.getMethods.foreach(m => println(...
355Reflection/List methods
16scala
6qo31
package main import "fmt" import "regexp" func main() { str := "I am the original string"
356Regular expressions
0go
4zy52
var fso = new ActiveXObject("Scripting.FileSystemObject") fso.MoveFile("input.txt", "output.txt") fso.MoveFile("c:/input.txt", "c:/output.txt") fso.MoveFolder("docs", "mydocs") fso.MoveFolder("c:/docs", "c:/mydocs")
353Rename a file
10javascript
vdy25
var strReversed = "---------- Ice and Fire ------------\n\ \n\ fire, in end will world the say Some\n\ ice. in say Some\n\ desire of tasted I've what From\n\ fire. favor who those with hold I\n\ \n\ ... elided paragraph last ...\n\ \n\ Frost Robert -----------------------"; function reverseString(s) { return s.split...
349Reverse words in a string
10javascript
li9cf
import roman print(roman.toRoman(2022))
341Roman numerals/Encode
3python
g6p4h
import java.util.regex.*; def woodchuck = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?" def pepper = "Peter Piper picked a peck of pickled peppers" println "=== Regular-expression String syntax (/string/) ===" def woodRE = /[Ww]o\w+d/ def piperRE = /[Pp]\w+r/ assert woodRE instanceof Strin...
356Regular expressions
7groovy
lifc1
import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap;
348Return multiple values
9java
obo8d
struct list_node {int x; struct list_node *next;}; typedef struct list_node node; node * uniq(int *a, unsigned alen) {if (alen == 0) return NULL; node *start = malloc(sizeof(node)); if (start == NULL) exit(EXIT_FAILURE); start->x = a[0]; start->next = NULL; for (int i = 1 ; i < alen ; ++i) {node *n = ...
362Remove duplicate elements
5c
cos9c
import Text.Regex str = "I am a string" case matchRegex (mkRegex ".*string$") str of Just _ -> putStrLn $ "ends with 'string'" Nothing -> return ()
356Regular expressions
8haskell
qrhx9
null
353Rename a file
11kotlin
te8f0
extension Int { init(romanNumerals: String) { let values = [ ( "M", 1000), ("CM", 900), ( "D", 500), ("CD", 400), ( "C", 100), ("XC", 90), ( "L", 50), ("XL", 40), ( "X", 10), (...
340Roman numerals/Decode
17swift
b2skd
null
348Return multiple values
10javascript
twtfm
package main import ( "fmt" "strings" ) func rep(s string) int { for x := len(s) / 2; x > 0; x-- { if strings.HasPrefix(s, s[x:]) { return x } } return 0 } const m = ` 1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1` func main() {...
358Rep-string
0go
h9cjq
fun reversedWords(s: String) = s.split(" ").filter { it.isNotEmpty() }.reversed().joinToString(" ") fun main() { val s = "Hey you, Bub!" println(reversedWords(s)) println() val sl = listOf( " ---------- Ice and Fire ------------ ", " ", " fi...
349Reverse words in a string
11kotlin
d1inz
as.roman(1666)
341Roman numerals/Encode
13r
vfj27
int main() { char *buffer; FILE *fh = fopen(, ); if ( fh != NULL ) { fseek(fh, 0L, SEEK_END); long s = ftell(fh); rewind(fh); buffer = malloc(s); if ( buffer != NULL ) { fread(buffer, s, 1, fh); fclose(fh); fh = NULL; fwrite(buffer, s, 1, stdout); ...
363Read entire file
5c
liscy
import Data.List (inits, maximumBy) import Data.Maybe (fromMaybe) repstring :: String -> Maybe String repstring [] = Nothing repstring [_] = Nothing repstring xs | any (`notElem` "01") xs = Nothing | otherwise = longest xs where lxs = length xs lq2 = lxs `quot` 2 subrepeat x = (...
358Rep-string
8haskell
ibpor
null
348Return multiple values
11kotlin
xrxws
String str = "I am a string"; if (str.matches(".*string")) {
356Regular expressions
9java
p25b3
var subject = "Hello world!";
356Regular expressions
10javascript
xgjw9
sub repeat { my ($sub, $n) = @_; $sub->() for 1..$n; } sub example { print "Example\n"; } repeat(\&example, 4);
352Repeat
2perl
98zmn
os.rename( "input.txt", "output.txt" ) os.rename( "/input.txt", "/output.txt" ) os.rename( "docs", "mydocs" ) os.rename( "/docs", "/mydocs" )
353Rename a file
1lua
zwoty
package main import "fmt" func main() { a := []int{0} used := make(map[int]bool, 1001) used[0] = true used1000 := make(map[int]bool, 1001) used1000[0] = true for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ { next := a[n-1] - n if next < 1 || used[...
361Recaman's sequence
0go
co09g
typedef struct sMtx { int dim_x, dim_y; EL_Type *m_stor; EL_Type **mtx; } *Matrix, sMatrix; typedef struct sRvec { int dim_x; EL_Type *m_stor; } *RowVec, sRowVec; Matrix NewMatrix( int x_dim, int y_dim ) { int n; Matrix m; m = TALLOC( 1, sMatrix); n = x_dim * y_dim; m->...
364Reduced row echelon form
5c
zwbtx
(slurp "myfile.txt") (slurp "my-utf8-file.txt" "UTF-8")
363Read entire file
6clojure
4zn5o
public class RepString { static final String[] input = {"1001110011", "1110111011", "0010010010", "1010101010", "1111111111", "0100101101", "0100100", "101", "11", "00", "1", "0100101"}; public static void main(String[] args) { for (String s : input) System.out.printf("%s:%...
358Rep-string
9java
xgrwy
def rot13(s) s.tr('A-Za-z', 'N-ZA-Mn-za-m') end while line = ARGF.gets print rot13(line) end
338Rot-13
14ruby
j9q7x