code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
var array = []; array.push('abc'); array.push(123); array.push(new MyClass); console.log( array[2] );
1,037Collections
10javascript
vrp25
' Boolean Evaluations ' ' > Greater Than ' < Less Than ' >= Greater Than Or Equal To ' <= Less Than Or Equal To ' = Equal to x = 0 if x = 0 then print ' -------------------------- ' if/then/else if x = 0 then print else print end if ' -------------------------- ' not if x then print end if if not(x) then print ...
1,023Conditional structures
14ruby
hacjx
def zero(f) return lambda {|x| x} end Zero = lambda { |f| zero(f) } def succ(n) return lambda { |f| lambda { |x| f.(n.(f).(x)) } } end Three = succ(succ(succ(Zero))) def add(n, m) return lambda { |f| lambda { |x| m.(f).(n.(f).(x)) } } end def mult(n, m) return lambda { |f| lambda { |x| m.(n.(f)).(x) } } end...
1,039Church numerals
14ruby
fyldr
add (a, b) (x, y) = (a + x, b + y) sub (a, b) (x, y) = (a - x, b - y) magSqr (a, b) = (a ^^ 2) + (b ^^ 2) mag a = sqrt $ magSqr a mul (a, b) c = (a * c, b * c) div2 (a, b) c = (a / c, b / c) perp (a, b) = (negate b, a) norm a = a `div2` mag a circlePoints :: (Ord a, Floating a...
1,046Circles of given radius through two points
8haskell
6lm3k
package main import "fmt" var ( animalString = []string{"Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"} stemYYString = []string{"Yang", "Yin"} elementString = []string{"Wood", "Fire", "Earth", "Metal", "Water"} stemCh = []rune("") ...
1,048Chinese zodiac
0go
kekhz
int check_reg(const char *path) { struct stat sb; return stat(path, &sb) == 0 && S_ISREG(sb.st_mode); } int check_dir(const char *path) { struct stat sb; return stat(path, &sb) == 0 && S_ISDIR(sb.st_mode); } int main() { printf(, check_reg() ? : ); printf(, check_dir() ? : ); printf(, check_r...
1,053Check that file exists
5c
0nast
package main import ( "bufio" "flag" "fmt" "log" "net" "strings" "time" ) func main() { log.SetPrefix("chat: ") addr := flag.String("addr", "localhost:4000", "listen address") flag.Parse() log.Fatal(ListenAndServe(*addr)) }
1,051Chat server
0go
d38ne
import java.time.Month; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.stream.Collectors; public class Main { private static class Birthday { private Month month; private int day; public Birthday(Month month, int day) { this.month = m...
1,049Cheryl's birthday
9java
0nqse
import threading import time import random def worker(workernum, barrier): sleeptime = random.random() print('Starting worker '+str(workernum)++str(sleeptime)) time.sleep(sleeptime) print('Exiting worker'+str(workernum)) barrier.wait() sleeptime = random.random() print('Starting ...
1,043Checkpoint synchronization
3python
gkk4h
use strict; use warnings; use ntheory 'divisor_sum'; sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r } sub chowla { my($n) = @_; $n < 2 ? 0 : divisor_sum($n) - ($n + 1); } sub prime_cnt { my($n) = @_; my $cnt = 1; for (3..$n) { $cnt++ if $_%2 and chowla($_) == 0 } ...
1,041Chowla numbers
2perl
xonw8
use std::rc::Rc; use std::ops::{Add, Mul}; #[derive(Clone)] struct Church<'a, T: 'a> { runner: Rc<dyn Fn(Rc<dyn Fn(T) -> T + 'a>) -> Rc<dyn Fn(T) -> T + 'a> + 'a>, } impl<'a, T> Church<'a, T> { fn zero() -> Self { Church { runner: Rc::new(|_f| { Rc::new(|x| x) }...
1,039Church numerals
15rust
tm2fd
public class MyClass{
1,038Classes
9java
bw8k3
null
1,038Classes
10javascript
w8fe2
class Zodiac { final static String[] animals = ["Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"] final static String[] elements = ["Wood", "Fire", "Earth", "Metal", "Water"] final static String[] animalChars = ["", "", "", "", "", "", "", "", "", "", "",...
1,048Chinese zodiac
7groovy
gkg46
class ChatServer implements Runnable { private int port = 0 private List<Client> clientList = new ArrayList<>() ChatServer(int port) { this.port = port } @SuppressWarnings("GroovyInfiniteLoopStatement") @Override void run() { try { ServerSocket serverSocket = ne...
1,051Chat server
7groovy
0nwsh
import java.util.Arrays; public class Cholesky { public static double[][] chol(double[][] a){ int m = a.length; double[][] l = new double[m][m];
1,042Cholesky decomposition
9java
xoiwy
(() => { 'use strict';
1,049Cheryl's birthday
10javascript
d3inu
null
1,023Conditional structures
15rust
kelh5
package main import ( "fmt" "math/big" ) var one = big.NewInt(1) func crt(a, n []*big.Int) (*big.Int, error) { p := new(big.Int).Set(n[0]) for _, n1 := range n[1:] { p.Mul(p, n1) } var x, q, s, z big.Int for i, n1 := range n { q.Div(p, n1) z.GCD(nil, &s, n1, &q) ...
1,047Chinese remainder theorem
0go
xoqwf
func succ<A, B, C>(_ n: @escaping (@escaping (A) -> B) -> (C) -> A) -> (@escaping (A) -> B) -> (C) -> B { return {f in return {x in return f(n(f)(x)) } } } func zero<A, B>(_ a: A) -> (B) -> B { return {b in return b } } func three<A>(_ f: @escaping (A) -> A) -> (A) -> A { return {x in ...
1,039Church numerals
17swift
d6cnh
class MyClass(val myInt: Int) { fun treble(): Int = myInt * 3 } fun main(args: Array<String>) { val mc = MyClass(24) print("${mc.myInt}, ${mc.treble()}") }
1,038Classes
11kotlin
rbwgo
var funcs: [() -> Int] = [] for var i = 0; i < 10; i++ { funcs.append({ i * i }) } println(funcs[3]())
1,033Closures/Value capture
17swift
kedhx
import Data.Array (Array, listArray, (!)) ats :: Array Int (Char, String) ats = listArray (0, 9) $ zip "" (words "ji y bng dng w j gng xn rn gi") ads :: Array Int (String, String) ads = listArray (0, 11) $ zip (chars "") ( words $ "z chu yn mo chn s " ...
1,048Chinese zodiac
8haskell
n3nie
(dorun (map #(.exists (clojure.java.io/as-file %)) '("/input.txt" "/docs" "./input.txt" "./docs")))
1,053Check that file exists
6clojure
d3snb
import Network import System.IO import Control.Concurrent import qualified Data.Text as T import Data.Text (Text) import qualified Data.Text.IO as T import qualified Data.Map as M import Data.Map (Map) import Control.Monad.Reader import Control.Monad.Error import Control.Exception import Data.Monoid import Control.App...
1,051Chat server
8haskell
57lug
const cholesky = function (array) { const zeros = [...Array(array.length)].map( _ => Array(array.length).fill(0)); const L = zeros.map((row, r, xL) => row.map((v, c) => { const sum = row.reduce((s, _, i) => i < c ? s + xL[r][i] * xL[c][i] : s, 0); return xL[r][c] = c < r + 1 ? r === c ? Math.sqrt(array[r][r] - su...
1,042Cholesky decomposition
10javascript
otz86
require 'socket' class Workshop def initialize @sockets = {} end def add child, parent = UNIXSocket.pair wid = fork do child.close @sockets.each_value { |sibling| sibling.close } Signal.trap() { exit! } loop do...
1,043Checkpoint synchronization
14ruby
7ppri
import java.util.PriorityQueue fun main(args: Array<String>) {
1,037Collections
11kotlin
tmuf0
class ChineseRemainderTheorem { static int chineseRemainder(int[] n, int[] a) { int prod = 1 for (int i = 0; i < n.length; i++) { prod *= n[i] } int p, sm = 0 for (int i = 0; i < n.length; i++) { p = prod.intdiv(n[i]) sm += a[i] * mulInv(p...
1,047Chinese remainder theorem
7groovy
px1bo
import java.util.Objects; public class Circles { private static class Point { private final double x, y; public Point(Double x, Double y) { this.x = x; this.y = y; } public double distanceFrom(Point other) { double dx = x - other.x; ...
1,046Circles of given radius through two points
9java
n3fih
null
1,049Cheryl's birthday
11kotlin
es1a4
null
1,043Checkpoint synchronization
15rust
j1172
import java.util.{Random, Scanner} object CheckpointSync extends App { val in = new Scanner(System.in) private def runTasks(nTasks: Int): Unit = { for (i <- 0 until nTasks) { println("Starting task number " + (i + 1) + ".") runThreads() Worker.checkpoint() } } private def run...
1,043Checkpoint synchronization
16scala
bwwk6
use ntheory qw/forcomb/; forcomb { print "@_\n" } 5,3
1,031Combinations
2perl
vrq20
if (n == 12) "twelve" else "not twelve" today match { case Monday => Compute_Starting_Balance; case Friday => Compute_Ending_Balance; case Tuesday => Accumulate_Sales case _ => {} }
1,023Conditional structures
16scala
1qupf
import Control.Monad (zipWithM) egcd :: Int -> Int -> (Int, Int) egcd _ 0 = (1, 0) egcd a b = (t, s - q * t) where (s, t) = egcd b r (q, r) = a `quotRem` b modInv :: Int -> Int -> Either String Int modInv a b = case egcd a b of (x, y) | a * x + b * y == 1 -> Right x | otherwise -> ...
1,047Chinese remainder theorem
8haskell
y2m66
const hDist = (p1, p2) => Math.hypot(...p1.map((e, i) => e - p2[i])) / 2; const pAng = (p1, p2) => Math.atan(p1.map((e, i) => e - p2[i]).reduce((p, c) => c / p, 1)); const solveF = (p, r) => t => [r*Math.cos(t) + p[0], r*Math.sin(t) + p[1]]; const diamPoints = (p1, p2) => p1.map((e, i) => e + (p2[i] - e) / 2); const f...
1,046Circles of given radius through two points
10javascript
3cyz0
public class Zodiac { final static String animals[]={"Rat","Ox","Tiger","Rabbit","Dragon","Snake","Horse","Goat","Monkey","Rooster","Dog","Pig"}; final static String elements[]={"Wood","Fire","Earth","Metal","Water"}; final static String animalChars[]={"","","","","","","","","","","",""}; static String elementCha...
1,048Chinese zodiac
9java
qiqxa
import java.io.*; import java.net.*; import java.util.*; public class ChatServer implements Runnable { private int port = 0; private List<Client> clients = new ArrayList<Client>(); public ChatServer(int port) { this.port = port; } public void run() { try { ServerSocket ss = new ServerSock...
1,051Chat server
9java
9v3mu
use Math::BigRat try=>"GMP"; sub taneval { my($coef,$f) = @_; $f = Math::BigRat->new($f) unless ref($f); return 0 if $coef == 0; return $f if $coef == 1; return -taneval(-$coef, $f) if $coef < 0; my($a,$b) = ( taneval($coef>>1, $f), taneval($coef-($coef>>1),$f) ); ($a+$b)/(1-$a*$b); } sub tans { my @x...
1,050Check Machin-like formulas
2perl
572u2
null
1,042Cholesky decomposition
11kotlin
pxqb6
null
1,049Cheryl's birthday
1lua
w0aea
from sympy import divisors def chowla(n): return 0 if n < 2 else sum(divisors(n, generator=True)) - 1 -n def is_prime(n): return chowla(n) == 0 def primes_to(n): return sum(chowla(i) == 0 for i in range(2, n)) def perfect_between(n, m): c = 0 print(f) for i in range(n, m): if i > 1 a...
1,041Chowla numbers
3python
qidxi
myclass = setmetatable({ __index = function(z,i) return myclass[i] end,
1,038Classes
1lua
7pxru
(() => { "use strict";
1,048Chinese zodiac
10javascript
iziol
const net = require("net"); const EventEmitter = require("events").EventEmitter; class ChatServer { constructor() { this.chatters = {}; this.server = net.createServer(this.handleConnection.bind(this)); this.server.listen(1212, "localhost"); } isNicknameLegal(nickname) {
1,051Chat server
10javascript
urcvb
int main() { printf(, 'a'); printf(, 97); return 0; }
1,054Character codes
5c
d3qnv
import static java.util.Arrays.stream; public class ChineseRemainderTheorem { public static int chineseRemainder(int[] n, int[] a) { int prod = stream(n).reduce(1, (i, j) -> i * j); int p, sm = 0; for (int i = 0; i < n.length; i++) { p = prod / n[i]; sm += a[i] * ...
1,047Chinese remainder theorem
9java
d6fn9
import re from fractions import Fraction from pprint import pprint as pp equationtext = '''\ pi/4 = arctan(1/2) + arctan(1/3) pi/4 = 2*arctan(1/3) + arctan(1/7) pi/4 = 4*arctan(1/5) - arctan(1/239) pi/4 = 5*arctan(1/7) + 2*arctan(3/79) pi/4 = 5*arctan(29/278) + 7*arctan(3/79) pi/4 = arctan(1/2) + arctan(...
1,050Check Machin-like formulas
3python
4jv5k
sub filter { my($test,@dates) = @_; my(%M,%D,@filtered); for my $date (@dates) { my($mon,$day) = split '-', $date; $M{$mon}{cnt}++; $D{$day}{cnt}++; push @{$M{$mon}{day}}, $day; push @{$D{$day}{mon}}, $mon; push @{$M{$mon}{bday}}, "$mon-$day"; ...
1,049Cheryl's birthday
2perl
cum9a
collection = {0, '1'} print(collection[1])
1,037Collections
1lua
z95ty
<?php $a=array(1,2,3,4,5); $k=3; $n=5; $c=array_splice($a, $k); $b=array_splice($a, 0, $k); $j=$k-1; print_r($b); while (1) { $m=array_search($b[$j]+1,$c); if ($m!==false) { $c[$m]-=1; $b[$j]=$b[$j]+1; print_r($b); } if ($b[$k-1]=...
1,031Combinations
12php
0dvsp
function crt(num, rem) { let sum = 0; const prod = num.reduce((a, c) => a * c, 1); for (let i = 0; i < num.length; i++) { const [ni, ri] = [num[i], rem[i]]; const p = Math.floor(prod / ni); sum += ri * p * mulInv(p, ni); } return sum % prod; } function mulInv(a, b) { const b0 = b; let [x0, x...
1,047Chinese remainder theorem
10javascript
6ly38
null
1,046Circles of given radius through two points
11kotlin
sn8q7
null
1,048Chinese zodiac
11kotlin
1q1pd
import java.io.BufferedReader import java.io.IOException import java.io.InputStreamReader import java.io.OutputStreamWriter import java.io.Writer import java.net.ServerSocket import java.net.Socket import java.util.ArrayList import java.util.Collections class ChatServer private constructor(private val port: Int) : Run...
1,051Chat server
11kotlin
zmnts
library(Rmpfr) prec <- 1000 `%:%` <- function(e1, e2) '/'(mpfr(e1, prec), mpfr(e2, prec)) tanident_1 <- function(x) identical(round(tan(eval(parse(text = gsub("/", "%:%", deparse(substitute(x)))))), (prec/10)), mpfr(1, prec))
1,050Check Machin-like formulas
13r
249lg
(print (int \a)) (print (char 97)) (print (int \)) (print (char 960)) (print (.codePointAt "" 0)) (print (String. (int-array 1 119136) 0 1))
1,054Character codes
6clojure
6ci3q
def chowla(n) sum = 0 i = 2 while i * i <= n do if n % i == 0 then sum = sum + i j = n / i if i!= j then sum = sum + j end end i = i + 1 end return sum end def main for n in 1 .. 37 do puts % [n, ch...
1,041Chowla numbers
14ruby
0dtsu
use strict; use warnings; use POSIX qw(ceil); sub dist { my ($a, $b) = @_; return sqrt(($a->[0] - $b->[0])**2 + ($a->[1] - $b->[1])**2) } sub closest_pair_simple { my @points = @{ shift @_ }; my ($a, $b, $d) = ( $points[0], $points[1], dist($points[0], $points[1]) ); while( @points ) ...
1,036Closest-pair problem
2perl
9uhmn
local ANIMALS = {"Rat","Ox","Tiger","Rabbit","Dragon","Snake","Horse","Goat","Monkey","Rooster","Dog","Pig"} local ELEMENTS = {"Wood","Fire","Earth","Metal","Water"} function element(year) local idx = math.floor(((year - 4) % 10) / 2) return ELEMENTS[idx + 1] end function animal(year) local idx = (year - ...
1,048Chinese zodiac
1lua
asa1v
package main import ( "fmt" "image" "image/color" "image/draw" "image/gif" "log" "math" "math/rand" "os" "time" ) var bwPalette = color.Palette{ color.Transparent, color.White, color.RGBA{R: 0xff, A: 0xff}, color.RGBA{G: 0xff, A: 0xff}, color.RGBA{B: 0xff, A: 0xff}, } func main() { const ( width ...
1,052Chaos game
0go
jp57d
'''Cheryl's Birthday''' from itertools import groupby from re import split def main(): '''Derivation of the date.''' month, day = 0, 1 print( uniquePairing(month)( uniquePairing(day)( month...
1,049Cheryl's birthday
3python
l59cv
null
1,047Chinese remainder theorem
11kotlin
0d8sf
object ChowlaNumbers { def main(args: Array[String]): Unit = { println("Chowla Numbers...") for(n <- 1 to 37){println(s"$n: ${chowlaNum(n)}")} println("\nPrime Counts...") for(i <- (2 to 7).map(math.pow(10, _).toInt)){println(f"$i%,d: ${primesPar(i).size}%,d")} println("\nPerfect Numbers...") ...
1,041Chowla numbers
16scala
n3yic
import javafx.animation.AnimationTimer import javafx.application.Application import javafx.scene.Scene import javafx.scene.layout.Pane import javafx.scene.paint.Color import javafx.scene.shape.Circle import javafx.stage.Stage class ChaosGame extends Application { final randomNumberGenerator = new Random() @O...
1,052Chaos game
7groovy
57cuv
options <- dplyr::tibble(mon = rep(c("May", "June", "July", "August"),times = c(3,2,2,3)), day = c(15, 16, 19, 17, 18, 14, 16, 14, 15, 17)) okMonths <- c() for (i in unique(options$mon)){ if(all(options$day[options$mon == i]%in% options$day[options$mon!= i])) {okMonths <- c(okMonths, i)} } ...
1,049Cheryl's birthday
13r
yl36h
import Foundation @inlinable public func chowla<T: BinaryInteger>(n: T) -> T { stride(from: 2, to: T(Double(n).squareRoot()+1), by: 1) .lazy .filter({ n% $0 == 0 }) .reduce(0, {(s: T, m: T) in m*m == n? s + m: s + m + (n / m) }) } extension Dictionary where Key == ClosedRange<Int> { subscrip...
1,041Chowla numbers
17swift
snfqt
function distance(p1, p2) local dx = (p1.x-p2.x) local dy = (p1.y-p2.y) return math.sqrt(dx*dx + dy*dy) end function findCircles(p1, p2, radius) local seperation = distance(p1, p2) if seperation == 0.0 then if radius == 0.0 then print("No circles can be drawn through ("..p1.x.."...
1,046Circles of given radius through two points
1lua
0dosd
import Control.Monad (replicateM) import Control.Monad.Random (fromList) type Point = (Float,Float) type Transformations = [(Point -> Point, Float)] gameOfChaos :: MonadRandom m => Int -> Transformations -> Point -> m [Point] gameOfChaos n transformations x = iterateA (fromList transformations) x where iterateA f...
1,052Chaos game
8haskell
ofx8p
null
1,047Chinese remainder theorem
1lua
8fo0e
import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.Timer; public class ChaosGame extends JPanel { static class ColoredPoint extends Point { int colorIndex; ColoredPoint(int x, int y, int idx) { super(x, y); colorIndex = ...
1,052Chaos game
9java
w0bej
use 5.010; use strict; use warnings; use threads; use threads::shared; use IO::Socket::INET; use Time::HiRes qw(sleep ualarm); my $HOST = "localhost"; my $PORT = 4004; my @open; my %users : shared; sub broadcast { my ($id, $message) = @_; print "$message\n"; foreach my $i (keys %users) { if ($i...
1,051Chat server
2perl
be7k4
<html> <head> <meta charset="UTF-8"> <title>Chaos Game</title> </head> <body> <p> <canvas id="sierpinski" width=400 height=346></canvas> </p> <p> <button onclick="chaosGame()">Click here to see a Sierpiski triangle</button> </p> <script> function chaosGame() { var canv = document.getElementById('sierpinski...
1,052Chaos game
10javascript
8dw0l
dates = [ [, 15], [, 16], [, 19], [, 17], [, 18], [, 14], [, 16], [, 14], [, 15], [, 17], ] print dates.length, uniqueMonths = dates.group_by { |m,d| d } .select { |k,v| v.size == 1 } .map { |k,v| v.flatten } .map { ...
1,049Cheryl's birthday
14ruby
vgl2n
sub zodiac { my $year = shift; my @animals = qw/Rat Ox Tiger Rabbit Dragon Snake Horse Goat Monkey Rooster Dog Pig/; my @elements = qw/Wood Fire Earth Metal Water/; my @terrestrial_han = qw/ /; my @terrestrial_pinyin = qw/z chu yn mo chn s w wi shn yu x hi/; my @celestial_han = qw/ /; my...
1,048Chinese zodiac
2perl
mvmyz
null
1,052Chaos game
11kotlin
berkb
null
1,049Cheryl's birthday
15rust
ur2vj
import java.time.format.DateTimeFormatter import java.time.{LocalDate, Month} object Cheryl { def main(args: Array[String]): Unit = { val choices = List( LocalDate.of(2019, Month.MAY, 15), LocalDate.of(2019, Month.MAY, 16), LocalDate.of(2019, Month.MAY, 19), LocalDate.of(2019, Month.JUNE...
1,049Cheryl's birthday
16scala
gh54i
from random import randint, randrange from operator import itemgetter, attrgetter infinity = float('inf') def bruteForceClosestPair(point): numPoints = len(point) if numPoints < 2: return infinity, (None, None) return min( ((abs(point[i] - point[j]), (point[i], point[j])) for i ...
1,036Closest-pair problem
3python
c5k9q
math.randomseed( os.time() ) colors, orig = { { 255, 0, 0 }, { 0, 255, 0 }, { 0, 0, 255 } }, {} function love.load() wid, hei = love.graphics.getWidth(), love.graphics.getHeight() orig[1] = { wid / 2, 3 } orig[2] = { 3, hei - 3 } orig[3] = { wid - 3, hei - 3 } local w, h = math.random( 10, 40 ), m...
1,052Chaos game
1lua
pw7bw
sub cholesky { my $matrix = shift; my $chol = [ map { [(0) x @$matrix ] } @$matrix ]; for my $row (0..@$matrix-1) { for my $col (0..$row) { my $x = $$matrix[$row][$col]; $x -= $$chol[$row][$_]*$$chol[$col][$_] for 0..$col; $$chol[$row][$col] = $row == $col ? sqrt $x : $x/$$chol[$col][...
1,042Cholesky decomposition
2perl
y2v6u
CASE WHEN a THEN b ELSE c END DECLARE @n INT SET @n=124 print CASE WHEN @n=123 THEN 'equal' ELSE 'not equal' END --If/ElseIf expression SET @n=5 print CASE WHEN @n=3 THEN 'Three' WHEN @n=4 THEN 'Four' ELSE 'Other' END
1,023Conditional structures
19sql
w8gex
closest_pair_brute <-function(x,y,plotxy=F) { xy = cbind(x,y) cp = bruteforce(xy) cat("\n\nShortest path found = \n From:\t\t(",cp[1],',',cp[2],")\n To:\t\t(",cp[3],',',cp[4],")\n Distance:\t",cp[5],"\n\n",sep="") if(plotxy) { plot(x,y,pch=19,col='black',main="Closest Pair", asp=1) poin...
1,036Closest-pair problem
13r
6lr3e
import socket import thread import time HOST = PORT = 4004 def accept(conn): def threaded(): while True: conn.send() try: name = conn.recv(1024).strip() except socket.error: continue if name in users: con...
1,051Chat server
3python
pwjbm
struct MonthDay: CustomStringConvertible { static let months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ] var month: Int var day: Int var description: String { "\(MonthDay.months[month - 1]) \(day)" } private func i...
1,049Cheryl's birthday
17swift
24clj
>>> from itertools import combinations >>> list(combinations(range(5),3)) [(0, 1, 2), (0, 1, 3), (0, 1, 4), (0, 2, 3), (0, 2, 4), (0, 3, 4), (1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
1,031Combinations
3python
u7svd
package main import ( "fmt" "os" ) func printStat(p string) { switch i, err := os.Stat(p); { case err != nil: fmt.Println(err) case i.IsDir(): fmt.Println(p, "is a directory") default: fmt.Println(p, "is a file") } } func main() { printStat("input.txt") pri...
1,053Check that file exists
0go
urmvt
println new File('input.txt').exists() println new File('/input.txt').exists() println new File('docs').exists() println new File('/docs').exists()
1,053Check that file exists
7groovy
9vtm4
chat_loop <- function(server, sockets, delay = 0.5) { repeat { Sys.sleep(delay) while (in_queue(server)) sockets <- new_socket_entry(server, sockets) sockets <- check_messages(sockets) if (nrow(sockets) == 0) next ...
1,051Chat server
13r
jp478
use ntheory qw/chinese/; say chinese([2,3], [3,5], [2,7]);
1,047Chinese remainder theorem
2perl
5j4u2
import System.Directory (doesFileExist, doesDirectoryExist) check :: (FilePath -> IO Bool) -> FilePath -> IO () check p s = do result <- p s putStrLn $ s ++ if result then " does exist" else " does not exist" main :: IO () main = do check doesFileExist "input.txt" check doesDirectoryExist ...
1,053Check that file exists
8haskell
w0ked
print(combn(0:4, 3))
1,031Combinations
13r
c5e95
{ package MyClass; sub new { my $class = shift; bless {variable => 0}, $class; } sub some_method { my $self = shift; $self->{variable} = 1; } }
1,038Classes
2perl
d6lnw
from __future__ import print_function from datetime import datetime pinyin = { '': 'ji', '': 'y', '': 'bng', '': 'dng', '': 'w', '': 'j', '': 'gng', '': 'xn', '': 'rn', '': 'gi', '': 'z', '': 'chu', '': 'yn', '': 'mo', '': 'chn', '': 's', '': 'w', '': 'wi', '': 'shn', '': 'yu',...
1,048Chinese zodiac
3python
9u9mf
use Imager; my $width = 1000; my $height = 1000; my @points = ( [ $width/2, 0], [ 0, $height-1], [$height-1, $height-1], ); my $img = Imager->new( xsize => $width, ysize => $height, channels => 3, ...
1,052Chaos game
2perl
6cd36
require 'gserver' class ChatServer < GServer def initialize *args super @chatters = [] @mutex = Mutex.new end def broadcast message, sender = nil message = message.strip << @mutex.synchronize do @chatters.each do |chatter| begin chatter.pri...
1,051Chat server
14ruby
aqk1s
from __future__ import print_function from pprint import pprint from math import sqrt def cholesky(A): L = [[0.0] * len(A) for _ in xrange(len(A))] for i in xrange(len(A)): for j in xrange(i+1): s = sum(L[i][k] * L[j][k] for k in xrange(j)) L[i][j] = sqrt(A[i][i] - s) if (i ==...
1,042Cholesky decomposition
3python
mvuyh
def chinese_remainder(n, a): sum = 0 prod = reduce(lambda a, b: a*b, n) for n_i, a_i in zip(n, a): p = prod / n_i sum += a_i * mul_inv(p, n_i) * p return sum% prod def mul_inv(a, b): b0 = b x0, x1 = 0, 1 if b == 1: return 1 while a > 1: q = a / b a, b =...
1,047Chinese remainder theorem
3python
4hg5k
class MyClass { public static $classVar; public $instanceVar; function __construct() { $this->instanceVar = 0; } function someMethod() { $this->instanceVar = 1; self::$classVar = 3; } } $myObj = new MyClass();
1,038Classes
12php
j1q7z