code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
COMPILE_TIME_ASSERT(sizeof(long)==8); int main() { COMPILE_TIME_ASSERT(sizeof(int)==4); }
572Metaprogramming
5c
o4780
(defn take-random [n coll] (->> (repeatedly #(rand-nth coll)) distinct (take n ,))) (defn postwalk-fs "Depth first post-order traversal of form, apply successive fs at each level. (f1 (map f2 [..]))" [[f & fs] form] (f (if (and (seq fs) (coll? form)) (into (empty form) (map (partial pos...
568Minesweeper game
6clojure
cwi9b
import java.math.BigInteger; import java.util.ArrayList; import java.util.List;
567Minimum positive multiple in base 10 using only 0 and 1
9java
jfc7c
package main import ( "fmt" "math/rand" "time" ) func main() {
569Mind boggling card trick
0go
nrpi1
(loop for count from 1 for x in '(1 2 3 4 5) summing x into sum summing (* x x) into sum-of-squares finally (return (let* ((mean (/ sum count)) (spl-var (- (* count sum-of-squares) (* sum sum))) (spl-dev (sqrt (/ spl-var (1- count))))) ...
572Metaprogramming
6clojure
thpfv
import java.math.BigInteger; public class PowMod { public static void main(String[] args){ BigInteger a = new BigInteger( "2988348162058574136915891421498819466320163312926952423791023078876139"); BigInteger b = new BigInteger( "2351399303373464486466122544523690094744975233415544072992...
566Modular exponentiation
9java
3b0zg
struct timeval start, last; inline int64_t tv_to_u(struct timeval s) { return s.tv_sec * 1000000 + s.tv_usec; } inline struct timeval u_to_tv(int64_t x) { struct timeval s; s.tv_sec = x / 1000000; s.tv_usec = x % 1000000; return s; } void draw(int dir, int64_t period, int64_t cur, int64_t next) { int len = 40 ...
573Metronome
5c
1y9pj
import System.Random (randomRIO) import Data.List (partition) import Data.Monoid ((<>)) main :: IO [Int] main = do ns <- knuthShuffle [1 .. 52] let (rs_, bs_, discards) = threeStacks (rb <$> ns) nSwap <- randomRIO (1, min (length rs_) (length bs_)) let (rs, bs) = exchange nSwap rs_ bs_ let rrs = ...
569Mind boggling card trick
8haskell
u0fv2
package main import ( "fmt" "math/big" ) var names = [10]string{"Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead"} func lucas(b int64) { fmt.Printf("Lucas sequence for%s ratio, where b =%d:\n", names[b], b) fmt.Print("First 15 elements: ") var x0...
574Metallic ratios
0go
htzjq
null
566Modular exponentiation
11kotlin
nreij
class Modulo include Comparable def initialize(n = 0, m = 13) @n, @m = n % m, m end def to_i @n end def <=>(other_n) @n <=> other_n.to_i end [:+,:-,:*,:**].each do |meth| define_method(meth) { |other_n| Modulo.new(@n.send(meth, other_n.to_i), @m) } end def coerce(numeric) [n...
564Modular arithmetic
14ruby
58muj
>>> size = 12 >>> width = len(str(size**2)) >>> for row in range(-1,size+1): if row==0: print(*width + +*((width+1)*size-1)) else: print(.join(% ((width,) + ((,) if row==-1 and col==0 else (row,) if row>0 and col==0 else (col,) if row==-1 else (,) ...
560Multiplication tables
3python
svwq9
(() => { 'use strict'; const main = () => { const
569Mind boggling card trick
10javascript
vsd25
class MetallicRatios { private static List<String> names = new ArrayList<>() static { names.add("Platinum") names.add("Golden") names.add("Silver") names.add("Bronze") names.add("Copper") names.add("Nickel") names.add("Aluminum") names.add("Iron") ...
574Metallic ratios
7groovy
4oi5f
import java.math.BigInteger fun main() { for (n in testCases) { val result = getA004290(n) println("A004290($n) = $result = $n * ${result / n.toBigInteger()}") } } private val testCases: List<Int> get() { val testCases: MutableList<Int> = ArrayList() for (i in 1..10) { ...
567Minimum positive multiple in base 10 using only 0 and 1
11kotlin
583ua
object ModularArithmetic extends App { private val x = new ModInt(10, 13) private val y = f(x) private def f[T](x: Ring[T]) = (x ^ 100) + x + x.one private trait Ring[T] { def +(rhs: Ring[T]): Ring[T] def *(rhs: Ring[T]): Ring[T] def one: Ring[T] def ^(p: Int): Ring[T] = { require(p >...
564Modular arithmetic
16scala
7d2r9
null
569Mind boggling card trick
11kotlin
thef0
package main import "fmt" func contains(is []int, s int) bool { for _, i := range is { if s == i { return true } } return false } func mianChowla(n int) []int { mc := make([]int, n) mc[0] = 1 is := []int{2} var sum int for i := 1; i < n; i++ { le :=...
571Mian-Chowla sequence
0go
vsi2m
import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.util.ArrayList; import java.util.List; public class MetallicRatios { private static String[] ratioDescription = new String[] {"Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminum", "Iron", "Tin",...
574Metallic ratios
9java
xl2wy
function array1D(n, v) local tbl = {} for i=1,n do table.insert(tbl, v) end return tbl end function array2D(h, w, v) local tbl = {} for i=1,h do table.insert(tbl, array1D(w, v)) end return tbl end function mod(m, n) m = math.floor(m) local result = m % n if ...
567Minimum positive multiple in base 10 using only 0 and 1
1lua
4o65c
multiplication_table <- function(n=12) { one_to_n <- 1:n x <- matrix(one_to_n)%*% t(one_to_n) x[lower.tri(x)] <- 0 rownames(x) <- colnames(x) <- one_to_n print(as.table(x), zero.print="") invisible(x) } multiplication_table()
560Multiplication tables
13r
e9pad
import Data.Set (Set, fromList, insert, member) mianChowlas :: Int -> [Int] mianChowlas = reverse . snd . (iterate nextMC (fromList [2], [1]) !!) . subtract 1 nextMC :: (Set Int, [Int]) -> (Set Int, [Int]) nextMC (sumSet, mcs@(n:_)) = (foldr insert sumSet ((2 * m): fmap (m +) mcs), m: mcs) where valid x = ...
571Mian-Chowla sequence
8haskell
e9vai
package main import "fmt" type person struct{ name string age int } func copy(p person) person { return person{p.name, p.age} } func main() { p := person{"Dave", 40} fmt.Println(p) q := copy(p) fmt.Println(q) }
572Metaprogramming
0go
4od52
macro dowhile(condition, block) quote while true $(esc(block)) if!$(esc(condition)) break end end end end macro dountil(condition, block) quote while true $(esc(block)) if $(esc(condition)) ...
572Metaprogramming
8haskell
q25x9
import java.math.BigDecimal import java.math.BigInteger val names = listOf("Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead") fun lucas(b: Long) { println("Lucas sequence for ${names[b.toInt()]} ratio, where b = $b:") print("First 15 elements: ") var x0 = 1L ...
574Metallic ratios
11kotlin
p6yb6
package main import ( "bufio" "fmt" "math" "math/rand" "os" "strconv" "strings" "time" ) type cell struct { isMine bool display byte
568Minesweeper game
0go
b32kh
package main import ( "log" "os" "sync" "time" )
570Metered concurrency
0go
58ful
precedencegroup ExponentiationGroup { higherThan: MultiplicationPrecedence } infix operator **: ExponentiationGroup protocol Ring { associatedtype RingType: Numeric var one: Self { get } static func +(_ lhs: Self, _ rhs: Self) -> Self static func *(_ lhs: Self, _ rhs: Self) -> Self static func **(_ lhs:...
564Modular arithmetic
17swift
u0yvg
sub trick { my(@deck) = @_; my $result .= sprintf "%-28s @deck\n", 'Starting deck:'; my(@discard, @red, @black); deal(\@deck, \@discard, \@red, \@black); $result .= sprintf "%-28s @red\n", 'Red pile:'; $result .= sprintf "%-28s @black\n", 'Black pile:'; my $n = int rand(+@red < +@bl...
569Mind boggling card trick
2perl
kzchc
import java.util.Arrays; public class MianChowlaSequence { public static void main(String[] args) { long start = System.currentTimeMillis(); System.out.println("First 30 terms of the MianChowla sequence."); mianChowla(1, 30); System.out.println("Terms 91 through 100 of the MianChow...
571Mian-Chowla sequence
9java
htyjm
package main import ( "fmt" "time" ) func main() { var bpm = 72.0
573Metronome
0go
y1e64
class CountingSemaphore { private int count = 0 private final int max CountingSemaphore(int max) { this.max = max } synchronized int acquire() { while (count >= max) { wait() } ++count } synchronized int release() { if (count) { count--; notifyAll() } count ...
570Metered concurrency
7groovy
cw89i
import Control.Concurrent ( newQSem, signalQSem, waitQSem, threadDelay, forkIO, newEmptyMVar, putMVar, takeMVar, QSem, MVar ) import Control.Monad ( replicateM_ ) worker :: QSem -> MVar String -> Int -> IO () worker q m n = do waitQSem q putMVar m $ "Worker...
570Metered concurrency
8haskell
xl4w4
(() => { 'use strict';
571Mian-Chowla sequence
10javascript
am210
null
572Metaprogramming
11kotlin
7dzr4
use strict; use warnings; use feature qw(say state); use Math::AnyNum qw<:overload as_dec>; sub gen_lucas { my $b = shift; my $i = 0; return sub { state @seq = (state $v1 = 1, state $v2 = 1); ($v2, $v1) = ($v1, $v2 + $b*$v1) and push(@seq, $v1) unless defined $seq[$i+1]; return $seq...
574Metallic ratios
2perl
y1a6u
module MineSweeper ( Board , Cell(..) , CellState(..) , Pos , pos , coveredLens , coveredFlaggedLens , coveredMinedLens , xCoordLens , yCoordLens , emptyBoard , groupedByRows , displayCell , isLoss , isWin , exposeMines , openCell , flagCell , mineBoard , totalRows , ...
568Minesweeper game
8haskell
d7an4
import Control.Concurrent import Control.Concurrent.MVar import System.Process (runCommand) data Beep = Stop | Hi | Low type Pattern = [Beep] type BeatsPerMinute = Int minute = 60000000 pattern4_4 = [Hi, Low, Low, Low] pattern2_4 = [Hi, Low] pattern3_4 = [Hi, Low, Low] pattern6_8 = [Hi, Low, Low, Low, Low, L...
573Metronome
8haskell
ht3ju
import random n = 52 Black, Red = 'Black', 'Red' blacks = [Black] * (n reds = [Red] * (n pack = blacks + reds random.shuffle(pack) black_stack, red_stack, discard = [], [], [] while pack: top = pack.pop() if top == Black: black_stack.append(pack.pop()) else: red_stack.append(pack.pop(...
569Mind boggling card trick
3python
b3lkr
class "foo" : inherits "bar" { }
572Metaprogramming
1lua
jf371
typedef struct { unsigned char r, g, b; } rgb_t; typedef struct { int w, h; rgb_t **pix; } image_t, *image; typedef struct { int r[256], g[256], b[256]; int n; } color_histo_t; int write_ppm(image im, char *fn) { FILE *fp = fopen(fn, ); if (!fp) return 0; fprintf(fp, , im->w, im->h); fwrite(im->pix[0], 1, siz...
575Median filter
5c
2qqlo
use strict; use warnings; use Math::AnyNum qw(:overload as_bin digits2num); for my $x (1..10, 95..105, 297, 576, 594, 891, 909, 999) { my $y; if ($x =~ /^9+$/) { $y = digits2num([(1) x (9 * length $x)],2) } else { while (1) { last unless as_bin(++$y) % $x } } printf "%4d:%28s %s\n", $x, ...
567Minimum positive multiple in base 10 using only 0 and 1
2perl
o4p8x
use bigint; sub expmod { my($a, $b, $n) = @_; my $c = 1; do { ($c *= $a) %= $n if $b % 2; ($a *= $a) %= $n; } while ($b = int $b/2); $c; } my $a = 2988348162058574136915891421498819466320163312926952423791023078876139; my $b = 2351399303373464486466122544523690094744975233415544072...
566Modular exponentiation
2perl
7dcrh
public class CountingSemaphore{ private int lockCount = 0; private int maxCount; CountingSemaphore(int Max){ maxCount = Max; } public synchronized void acquire() throws InterruptedException{ while( lockCount >= maxCount){ wait(); } lockCount++; } public synchroniz...
570Metered concurrency
9java
b3ck3
magictrick<-function(){ deck=c(rep("B",26),rep("R",26)) deck=sample(deck,52) blackpile=character(0) redpile=character(0) discardpile=character(0) while(length(deck)>0){ if(deck[1]=="B"){ blackpile=c(blackpile,deck[2]) deck=deck[-2] }else{ redpile=c(redpile,deck[2]) deck=deck[...
569Mind boggling card trick
13r
7dyry
null
571Mian-Chowla sequence
11kotlin
4of57
from itertools import count, islice from _pydecimal import getcontext, Decimal def metallic_ratio(b): m, n = 1, 1 while True: yield m, n m, n = m*b + n, m def stable(b, prec): def to_decimal(b): for m,n in metallic_ratio(b): yield Decimal(m)/Decimal(n) getcontext()...
574Metallic ratios
3python
maeyh
--------------------------------- START of Main.java ---------------------------------
568Minesweeper game
9java
svjq0
class Metronome{ double bpm; int measure, counter; public Metronome(double bpm, int measure){ this.bpm = bpm; this.measure = measure; } public void start(){ while(true){ try { Thread.sleep((long)(1000*(60.0/bpm))); }catch(InterruptedException e) { e.printStackTrace(); } counter++; if ...
573Metronome
9java
58iuf
null
570Metered concurrency
11kotlin
rn3go
bool miller_rabin_test(mpz_t n, int j);
576Miller–Rabin primality test
5c
p63by
package main
575Median filter
0go
q22xz
def getA004290(n): if n < 2: return 1 arr = [[0 for _ in range(n)] for _ in range(n)] arr[0][0] = 1 arr[0][1] = 1 m = 0 while True: m += 1 if arr[m - 1][-10 ** m% n] == 1: break arr[m][0] = 1 for k in range(1, n): arr[m][k] = max([a...
567Minimum positive multiple in base 10 using only 0 and 1
3python
ig1of
<?php $a = '2988348162058574136915891421498819466320163312926952423791023078876139'; $b = '2351399303373464486466122544523690094744975233415544072992656881240319'; $m = '1' . str_repeat('0', 40); echo bcpowmod($a, $b, $m), ;
566Modular exponentiation
12php
fjxdh
null
573Metronome
11kotlin
cwq98
def multiplication_table(n) puts + ( * n) % [*1..n] puts + * n 1.upto(n) do |x| print % x 1.upto(x-1) {|y| print } x.upto(n) {|y| print % (x*y)} puts end end multiplication_table 12
560Multiplication tables
14ruby
85q01
use strict; use warnings; use feature 'say'; sub generate_mc { my($max) = @_; my $index = 0; my $test = 1; my %sums = (2 => 1); my @mc = 1; while ($test++) { my %these = %sums; map { next if ++$these{$_ + $test} > 1 } @mc[0..$index], $test; %sums = %these; ...
571Mian-Chowla sequence
2perl
igho3
package main import "fmt" type rs232p9 uint16 const ( CD9 rs232p9 = 1 << iota
577Memory layout of a data structure
0go
cwa9g
a = 2988348162058574136915891421498819466320163312926952423791023078876139 b = 2351399303373464486466122544523690094744975233415544072992656881240319 m = 10 ** 40 print(pow(a, b, m))
566Modular exponentiation
3python
jfl7p
deck = ([:black, :red] * 26 ).shuffle black_pile, red_pile, discard = [], [], [] until deck.empty? do discard << deck.pop discard.last == :black? black_pile << deck.pop: red_pile << deck.pop end x = rand( [black_pile.size, red_pile.size].min ) red_bunch = x.times.map{ red_pile.delete_at( rand( red_pile.size ))...
569Mind boggling card trick
14ruby
1yvpw
package UnicodeEllipsis; use Filter::Simple; FILTER_ONLY code => sub { s//../g };
572Metaprogramming
2perl
fjbd7
(ns test-p.core (:require [clojure.math.numeric-tower :as math]) (:require [clojure.set :as set])) (def WITNESSLOOP "witness") (def COMPOSITE "composite") (defn m* [p q m] " Computes (p*q) mod m " (mod (*' p q) m)) (defn power "modular exponentiation (i.e. b^e mod m" [b e m] (loop [b b, e e, x 1] (...
576Miller–Rabin primality test
6clojure
xlcwk
null
577Memory layout of a data structure
11kotlin
vsx21
require('bigdecimal') require('bigdecimal/util') def lucas(b) Enumerator.new do |yielder| xn2 = 1; yielder.yield(xn2) xn1 = 1; yielder.yield(xn1) loop { xn2, xn1 = xn1, b * xn1 + xn2; yielder.yield(xn1) } end end def metallic_ratio(b, precision) xn2 = xn1 = prev = this = 0 lucas(b).each.w...
574Metallic ratios
14ruby
cwx9k
null
575Median filter
11kotlin
8550q
without js -- (tasks) sequence sems = {} constant COUNTER = 1, QUEUE = 2 function semaphore(integer n) if n>0 then sems = append(sems,{n,{}}) return length(sems) else return 0 end if end function procedure acquire(integer id) if sems[id][COUNTER]=0 then task_suspend(t...
570Metered concurrency
2perl
d7pnw
const LIMIT: i32 = 12; fn main() { for i in 1..LIMIT+1 { print!("{:3}{}", i, if LIMIT - i == 0 {'\n'} else {' '}) } for i in 0..LIMIT+1 { print!("{}", if LIMIT - i == 0 {"+\n"} else {"----"}); } for i in 1..LIMIT+1 { for j in 1..LIMIT+1 { if j < i { ...
560Multiplication tables
15rust
o4s83
extern crate rand;
569Mind boggling card trick
15rust
amu14
from itertools import count, islice, chain import time def mian_chowla(): mc = [1] yield mc[-1] psums = set([2]) newsums = set([]) for trial in count(2): for n in chain(mc, [trial]): sum = n + trial if sum in psums: newsums.clear() bre...
571Mian-Chowla sequence
3python
nrkiz
package main import ( "fmt" "math" "sort" ) type Patient struct { id int lastName string }
578Merge and aggregate datasets
0go
wcyeg
null
560Multiplication tables
16scala
d7ong
from macropy.core.macros import * from macropy.core.quotes import macros, q, ast, u macros = Macros() @macros.expr def expand(tree, **kw): addition = 10 return q[lambda x: x * ast[tree] + u[addition]]
572Metaprogramming
3python
thpfw
int main() { int *ints = malloc(SIZEOF_MEMB*NMEMB); ints = realloc(ints, sizeof(int)*(NMEMB+1)); int *int2 = calloc(NMEMB, SIZEOF_MEMB); free(ints); free(int2); return 0; }
579Memory allocation
5c
lx1cy
import Data.List import Data.Maybe import System.IO (readFile) import Text.Read (readMaybe) import Control.Applicative ((<|>)) newtype DB = DB { entries :: [Patient] } deriving Show instance Semigroup DB where DB a <> DB b = normalize $ a <> b instance Monoid DB where mempty = DB [] normalize :: [Patient] -...
578Merge and aggregate datasets
8haskell
6ph3k
def mod(m, n) result = m % n if result < 0 then result = result + n end return result end def getA004290(n) if n == 1 then return 1 end arr = Array.new(n) { Array.new(n, 0) } arr[0][0] = 1 arr[0][1] = 1 m = 0 while true m = m + 1 if arr[m - 1]...
567Minimum positive multiple in base 10 using only 0 and 1
14ruby
d7ens
a = 2988348162058574136915891421498819466320163312926952423791023078876139 b = 2351399303373464486466122544523690094744975233415544072992656881240319 m = 10**40 puts a.pow(b, m)
566Modular exponentiation
14ruby
kzvhg
use num::bigint::BigInt; use num::bigint::ToBigInt;
566Modular exponentiation
15rust
b3ukx
use Time::HiRes qw(sleep gettimeofday); local $| = 1; my $beats_per_minute = shift || 72; my $beats_per_bar = shift || 4; my $i = 0; my $duration = 60 / $beats_per_minute; my $base_time = gettimeofday() + $duration; for (my $next_time = $base_time ; ; $next_time += $duration) { if ($i++ % $beats...
573Metronome
2perl
xlvw8
require 'set' n, ts, mc, sums = 100, [], [1], Set.new sums << 2 st = Time.now for i in (1 .. (n-1)) for j in mc[i-1]+1 .. Float::INFINITY mc[i] = j for k in (0 .. i) if (sums.include?(sum = mc[k]+j)) ts.clear break end ts << sum end if (ts.l...
571Mian-Chowla sequence
14ruby
fjpdr
'%C%' <- function(n, k) choose(n, k) 5 %C% 2
572Metaprogramming
13r
igjo5
use strict 'vars'; use warnings; use PDL; use PDL::Image2D; my $image = rpic 'plasma.png'; my $smoothed = med2d $image, ones(3,3), {Boundary => Truncate}; wpic $smoothed, 'plasma_median.png';
575Median filter
2perl
4oo5d
import scala.collection.mutable.ListBuffer object MinimumNumberOnlyZeroAndOne { def main(args: Array[String]): Unit = { for (n <- getTestCases) { val result = getA004290(n) println(s"A004290($n) = $result = $n * ${result / n}") } } def getTestCases: List[Int] = { val testCases = ListBuff...
567Minimum positive multiple in base 10 using only 0 and 1
16scala
3bszy
import scala.math.BigInt val a = BigInt( "2988348162058574136915891421498819466320163312926952423791023078876139") val b = BigInt( "2351399303373464486466122544523690094744975233415544072992656881240319") println(a.modPow(b, BigInt(10).pow(40)))
566Modular exponentiation
16scala
amg1n
import time import threading sem = threading.Semaphore(4) workers = [] running = 1 def worker(): me = threading.currentThread() while 1: sem.acquire() try: if not running: break print '%s acquired semaphore'% me.getName() time.sleep(2.0) ...
570Metered concurrency
3python
fj1de
MAX=1000 m[1]=1 for n in `seq 2 $MAX` do m[n]=1 for k in `seq 2 $n` do m[n]=$((m[n]-m[n/k])) done done echo 'The first 99 Mertens numbers are:' echo -n ' ' for n in `seq 1 99` do printf '%2d ' ${m[n]} test $((n%10)) -eq 9 && echo done zero=0 cross=0 for n in `seq 1 $MAX` do if [...
580Mertens function
4bash
fj5d8
use Bit::Vector::Minimal qw(); my $vec = Bit::Vector::Minimal->new(size => 24); my %rs232 = reverse ( 1 => 'PG Protective ground', 2 => 'TD Transmitted data', 3 => 'RD Received data', 4 => 'RTS Request to send', 5 => 'CTS Clear to send', 6 => 'DSR Data set ready', 7 => 'SG ...
577Memory layout of a data structure
2perl
0u2s4
import Image, ImageFilter im = Image.open('image.ppm') median = im.filter(ImageFilter.MedianFilter(3)) median.save('image2.ppm')
575Median filter
3python
gii4h
char * mid3(int n) { static char buf[32]; int l; sprintf(buf, , n > 0 ? n : -n); l = strlen(buf); if (l < 3 || !(l & 1)) return 0; l = l / 2 - 1; buf[l + 3] = 0; return buf + l; } int main(void) { int x[] = {123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, ...
581Middle three digits
5c
6pr32
public func mianChowla(n: Int) -> [Int] { var mc = Array(repeating: 0, count: n) var ls = [2: true] var sum = 0 mc[0] = 1 for i in 1..<n { var lsx = [Int]() jLoop: for j in (mc[i-1]+1)... { mc[i] = j for k in 0...i { sum = mc[k] + j if ls[sum]?? false { lsx =...
571Mian-Chowla sequence
17swift
d7bnh
from ctypes import Structure, c_int rs232_9pin = .split() rs232_25pin = ( ).split() class RS232_9pin(Structure): _fields_ = [(__, c_int, 1) for __ in rs232_9pin] class RS232_25pin(Structure): _fields_ = [(__, c_int, 1) for __ in rs232_25pin]
577Memory layout of a data structure
3python
85v0o
use warnings; use strict; { package Local::Field; use constant { REAL => 0, SHOW => 1, COUNT => 2, }; sub new { my ($class, $width, $height, $percent) = @_; my $field; for my $x (1 .. $width) { for my $y (1 .. $height) { $fie...
568Minesweeper game
2perl
9eomn
import BigInt func modPow<T: BinaryInteger>(n: T, e: T, m: T) -> T { guard e!= 0 else { return 1 } var res = T(1) var base = n% m var exp = e while true { if exp & 1 == 1 { res *= base res%= m } if exp == 1 { return res } exp /= 2 base *= base base%= m ...
566Modular exponentiation
17swift
ht2j0
require 'thread' class Semaphore def initialize(size = 1) @queue = SizedQueue.new(size) size.times { acquire } end def acquire tap { @queue.push(nil) } end def release tap { @queue.pop } end def count @queue.length end def synchronize release yield ensure acq...
570Metered concurrency
14ruby
zketw
null
570Metered concurrency
15rust
3bwz8
class IDVictim attr_accessor :name, :birthday, :gender, :hometown def self.new_element(element) attr_accessor element end end
572Metaprogramming
14ruby
3baz7
int* mertens_numbers(int max) { int* m = malloc((max + 1) * sizeof(int)); if (m == NULL) return m; m[1] = 1; for (int n = 2; n <= max; ++n) { m[n] = 1; for (int k = 2; k <= n; ++k) m[n] -= m[n/k]; } return m; } int main() { const int max = 1000; int* ...
580Mertens function
5c
zkgtx
class Pixmap def median_filter(radius=3) radius += 1 if radius.even? filtered = self.class.new(@width, @height) pb = ProgressBar.new(@height) if $DEBUG @height.times do |y| @width.times do |x| window = [] (x - radius).upto(x + radius).each do |win_x| (y - radius).upto(y...
575Median filter
14ruby
7ddri
import time def main(bpm = 72, bpb = 4): sleep = 60.0 / bpm counter = 0 while True: counter += 1 if counter% bpb: print 'tick' else: print 'TICK' time.sleep(sleep) main()
573Metronome
3python
q2uxi
class CountingSemaphore(var maxCount: Int) { private var lockCount = 0 def acquire(): Unit = { while ( { lockCount >= maxCount }) wait() lockCount += 1 } def release(): Unit = { if (lockCount > 0) { lockCount -= 1 notifyAll() } } def getCount: Int = lockCount } obje...
570Metered concurrency
16scala
masyc
null
572Metaprogramming
15rust
6pe3l