code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
const char *coin_err; typedef unsigned char byte; int is_hex(const char *s) { int i; for (i = 0; i < 64; i++) if (!isxdigit(s[i])) return 0; return 1; } void str_to_byte(const char *src, byte *dst, int n) { while (n--) sscanf(src + n * 2, , dst + n); } char* base58(byte *s, char *out) { static const char *tmpl = ; static char buf[40]; int c, i, n; if (!out) out = buf; out[n = 34] = 0; while (n--) { for (c = i = 0; i < 25; i++) { c = c * 256 + s[i]; s[i] = c / 58; c %= 58; } out[n] = tmpl[c]; } for (n = 0; out[n] == '1'; n++); memmove(out, out + n, 34 - n); return out; } char *coin_encode(const char *x, const char *y, char *out) { byte s[65]; byte rmd[5 + RIPEMD160_DIGEST_LENGTH]; if (!is_hex(x) || !(is_hex(y))) { coin_err = ; return 0; } s[0] = 4; str_to_byte(x, s + 1, 32); str_to_byte(y, s + 33, 32); rmd[0] = COIN_VER; RIPEMD160(SHA256(s, 65, 0), SHA256_DIGEST_LENGTH, rmd + 1); memcpy(rmd + 21, SHA256(SHA256(rmd, 21, 0), SHA256_DIGEST_LENGTH, 0), 4); return base58(rmd, out); } int main(void) { puts(coin_encode( , , 0)); return 0; }
1,093Bitcoin/public point to address
5c
yc06f
null
1,091Bitmap/Bézier curves/Quadratic
11kotlin
25tli
static int width, height; static BYTE bitmap[MAXSIZE][MAXSIZE]; static BYTE oldColor; static BYTE newColor; void floodFill(int i, int j) { if ( 0 <= i && i < height && 0 <= j && j < width && bitmap[i][j] == oldColor ) { bitmap[i][j] = newColor; floodFill(i-1,j); floodFill(i+1,j); floodFill(i,j-1); floodFill(i,j+1); } } void skipLine(FILE* file) { while(!ferror(file) && !feof(file) && fgetc(file) != '\n') ; } void skipCommentLines(FILE* file) { int c; int comment = ' while ((c = fgetc(file)) == comment) skipLine(file); ungetc(c,file); } readPortableBitMap(FILE* file) { int i,j; skipLine(file); skipCommentLines(file); fscanf(file,,&width); skipCommentLines(file); fscanf(file,,&height); skipCommentLines(file); if ( width <= MAXSIZE && height <= MAXSIZE ) for ( i = 0; i < height; i++ ) for ( j = 0; j < width; j++ ) fscanf(file,,&(bitmap[i][j])); else exit(EXIT_FAILURE); } void writePortableBitMap(FILE* file) { int i,j; fprintf(file,); fprintf(file,, width, height); for ( i = 0; i < height; i++ ) { for ( j = 0; j < width; j++ ) fprintf(file,, bitmap[i][j]); fprintf(file,); } } int main(void) { oldColor = 1; newColor = oldColor ? 0 : 1; readPortableBitMap(stdin); floodFill(height/2,width/2); writePortableBitMap(stdout); return EXIT_SUCCESS; }
1,094Bitmap/Flood fill
5c
v4d2o
function replace(input: string, key: number) : string { return input.replace(/([a-z])/g, ($1) => String.fromCharCode(($1.charCodeAt(0) + key + 26 - 97) % 26 + 97) ).replace(/([A-Z])/g, ($1) => String.fromCharCode(($1.charCodeAt(0) + key + 26 - 65) % 26 + 65)); }
1,083Caesar cipher
20typescript
sisqj
define('src_name', 'input.jpg'); define('dest_name', 'output.jpg'); $img = imagecreatefromjpeg(src_name); if(empty($img)){ echo 'Image could not be loaded!'; exit; } $black = imagecolorallocate($img, 0, 0, 0); $white = imagecolorallocate($img, 255, 255, 255); $width = imagesx($img); $height = imagesy($img); $array_lum = array(); $sum_lum = 0; $average_lum = 0; for($x = 0; $x < $width; $x++){ for($y = 0; $y < $height; $y++){ $color = imagecolorat($img, $x, $y); $r = ($color >> 16) & 0xFF; $g = ($color >> 8) & 0xFF; $b = $color & 0xFF; $array_lum[$x][$y] = ($r + $g + $b); $sum_lum += $array_lum[$x][$y]; } } $average_lum = $sum_lum / ($width * $height); for($x = 0; $x < $width; $x++){ for($y = 0; $y < $height; $y++){ if($array_lum[$x][$y] > $average_lum){ imagesetpixel($img, $x, $y, $white); } else{ imagesetpixel($img, $x, $y, $black); } } } imagejpeg($img, dest_name); if(!file_exists(dest_name)){ echo 'Image not saved! Check permission!'; }
1,089Bitmap/Histogram
12php
7k2rp
Bitmap.quadraticbezier = function(self, x1, y1, x2, y2, x3, y3, nseg) nseg = nseg or 10 local prevx, prevy, currx, curry for i = 0, nseg do local t = i / nseg local a, b, c = (1-t)^2, 2*t*(1-t), t^2 prevx, prevy = currx, curry currx = math.floor(a * x1 + b * x2 + c * x3 + 0.5) curry = math.floor(a * y1 + b * y2 + c * y3 + 0.5) if i > 0 then self:line(prevx, prevy, currx, curry) end end end local bitmap = Bitmap(61,21) bitmap:clear() bitmap:quadraticbezier( 1,1, 30,37, 59,1 ) bitmap:render({[0x000000]='.', [0xFFFFFFFF]='X'})
1,091Bitmap/Bézier curves/Quadratic
1lua
v4z2x
package raster
1,092Bitmap/Midpoint circle algorithm
0go
ludcw
void cubic_bezier( image img, unsigned int x1, unsigned int y1, unsigned int x2, unsigned int y2, unsigned int x3, unsigned int y3, unsigned int x4, unsigned int y4, color_component r, color_component g, color_component b );
1,095Bitmap/Bézier curves/Cubic
5c
ugdv4
int main() { int i, j; double degrees[] = { 0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38 }; const char * names = ; for (i = 0; i < 33; i++) { j = .5 + degrees[i] * 32 / 360; printf(, (j % 32) + 1, names + (j % 32) * 22, degrees[i]); } return 0; }
1,096Box the compass
5c
gjt45
module Circle where import Data.List type Point = (Int, Int) generateCirclePoints :: Point -> Int -> [Point] generateCirclePoints (x0, y0) radius = (x0, y0 + radius): (x0, y0 - radius): (x0 + radius, y0): (x0 - radius, y0): points where points = concatMap generatePoints $ unfoldr step initialValues generatePoints (x, y) = [(xop x0 x', yop y0 y') | (x', y') <- [(x, y), (y, x)], xop <- [(+), (-)], yop <- [(+), (-)]] initialValues = (1 - radius, 1, (-2) * radius, 0, radius) step (f, ddf_x, ddf_y, x, y) | x >= y = Nothing | otherwise = Just ((x', y'), (f', ddf_x', ddf_y', x', y')) where (f', ddf_y', y') | f >= 0 = (f + ddf_y' + ddf_x', ddf_y + 2, y - 1) | otherwise = (f + ddf_x, ddf_y, y) ddf_x' = ddf_x + 2 x' = x + 1
1,092Bitmap/Midpoint circle algorithm
8haskell
1w5ps
from PIL import Image image = Image.open() width, height = image.size amount = width * height total = 0 bw_image = Image.new('L', (width, height), 0) bm_image = Image.new('1', (width, height), 0) for h in range(0, height): for w in range(0, width): r, g, b = image.getpixel((w, h)) greyscale = int((r + g + b) / 3) total += greyscale bw_image.putpixel((w, h), gray_scale) avg = total / amount black = 0 white = 1 for h in range(0, height): for w in range(0, width): v = bw_image.getpixel((w, h)) if v >= avg: bm_image.putpixel((w, h), white) else: bm_image.putpixel((w, h), black) bw_image.show() bm_image.show()
1,089Bitmap/Histogram
3python
dzqn1
import java.awt.Color; public class MidPointCircle { private BasicBitmapStorage image; public MidPointCircle(final int imageWidth, final int imageHeight) { this.image = new BasicBitmapStorage(imageWidth, imageHeight); } private void drawCircle(final int centerX, final int centerY, final int radius) { int d = (5 - r * 4)/4; int x = 0; int y = radius; Color circleColor = Color.white; do { image.setPixel(centerX + x, centerY + y, circleColor); image.setPixel(centerX + x, centerY - y, circleColor); image.setPixel(centerX - x, centerY + y, circleColor); image.setPixel(centerX - x, centerY - y, circleColor); image.setPixel(centerX + y, centerY + x, circleColor); image.setPixel(centerX + y, centerY - x, circleColor); image.setPixel(centerX - y, centerY + x, circleColor); image.setPixel(centerX - y, centerY - x, circleColor); if (d < 0) { d += 2 * x + 1; } else { d += 2 * (x - y) + 1; y--; } x++; } while (x <= y); } }
1,092Bitmap/Midpoint circle algorithm
9java
7k9rj
const char *coin_err; int unbase58(const char *s, unsigned char *out) { static const char *tmpl = ; int i, j, c; const char *p; memset(out, 0, 25); for (i = 0; s[i]; i++) { if (!(p = strchr(tmpl, s[i]))) bail(); c = p - tmpl; for (j = 25; j--; ) { c += 58 * out[j]; out[j] = c % 256; c /= 256; } if (c) bail(); } return 1; } int valid(const char *s) { unsigned char dec[32], d1[SHA256_DIGEST_LENGTH], d2[SHA256_DIGEST_LENGTH]; coin_err = ; if (!unbase58(s, dec)) return 0; SHA256(SHA256(dec, 21, d1), SHA256_DIGEST_LENGTH, d2); if (memcmp(dec + 21, d2, 4)) bail(); return 1; } int main (void) { const char *s[] = { , , , , 0 }; int i; for (i = 0; s[i]; i++) { int status = valid(s[i]); printf(, s[i], status ? : coin_err); } return 0; }
1,097Bitcoin/address validation
5c
258lo
package main import ( "crypto/sha256" "encoding/hex" "errors" "fmt" "golang.org/x/crypto/ripemd160" )
1,093Bitcoin/public point to address
0go
1wup5
(require racket/draw) (define (draw-line dc p q) (match* (p q) [((list x y) (list s t)) (send dc draw-line x y s t)])) (define (draw-lines dc ps) (void (for/fold ([p0 (first ps)]) ([p (rest ps)]) (draw-line dc p0 p) p))) (define (int t p q) (define ((int1 t) x0 x1) (+ (* (- 1 t) x0) (* t x1))) (map (int1 t) p q)) (define (bezier-points p0 p1 p2) (for/list ([t (in-range 0.0 1.0 (/ 1.0 20))]) (int t (int t p0 p1) (int t p1 p2)))) (define bm (make-object bitmap% 17 17)) (define dc (new bitmap-dc% [bitmap bm])) (send dc set-smoothing 'unsmoothed) (send dc set-pen 1 'solid) (draw-lines dc (bezier-points '(16 1) '(1 4) '(3 16))) bm
1,091Bitmap/Bézier curves/Quadratic
3python
0ibsq
(require racket/draw) (define (draw-line dc p q) (match* (p q) [((list x y) (list s t)) (send dc draw-line x y s t)])) (define (draw-lines dc ps) (void (for/fold ([p0 (first ps)]) ([p (rest ps)]) (draw-line dc p0 p) p))) (define (int t p q) (define ((int1 t) x0 x1) (+ (* (- 1 t) x0) (* t x1))) (map (int1 t) p q)) (define (bezier-points p0 p1 p2) (for/list ([t (in-range 0.0 1.0 (/ 1.0 20))]) (int t (int t p0 p1) (int t p1 p2)))) (define bm (make-object bitmap% 17 17)) (define dc (new bitmap-dc% [bitmap bm])) (send dc set-smoothing 'unsmoothed) (send dc set-pen "red" 1 'solid) (draw-lines dc (bezier-points '(16 1) '(1 4) '(3 16))) bm
1,091Bitmap/Bézier curves/Quadratic
13r
ws7e5
function Bitmap:circle(x, y, r, c) local dx, dy, err = r, 0, 1-r while dx >= dy do self:set(x+dx, y+dy, c) self:set(x-dx, y+dy, c) self:set(x+dx, y-dy, c) self:set(x-dx, y-dy, c) self:set(x+dy, y+dx, c) self:set(x-dy, y+dx, c) self:set(x+dy, y-dx, c) self:set(x-dy, y-dx, c) dy = dy + 1 if err < 0 then err = err + 2 * dy + 1 else dx, err = dx-1, err + 2 * (dy - dx) + 1 end end end
1,092Bitmap/Midpoint circle algorithm
1lua
5r3u6
import Numeric (showIntAtBase) import Data.List (unfoldr) import Data.Binary (Word8) import Crypto.Hash.SHA256 as S (hash) import Crypto.Hash.RIPEMD160 as R (hash) import Data.ByteString (unpack, pack) publicPointToAddress :: Integer -> Integer -> String publicPointToAddress x y = let toBytes x = reverse $ unfoldr (\b -> if b == 0 then Nothing else Just (fromIntegral $ b `mod` 256, b `div` 256)) x ripe = 0: unpack (R.hash $ S.hash $ pack $ 4: toBytes x ++ toBytes y) ripe_checksum = take 4 $ unpack $ S.hash $ S.hash $ pack ripe addressAsList = ripe ++ ripe_checksum address = foldl (\v b -> v * 256 + fromIntegral b) 0 addressAsList base58Digits = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" in showIntAtBase 58 (base58Digits !!) address "" main = print $ publicPointToAddress 0x50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352 0x2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6
1,093Bitcoin/public point to address
8haskell
t6wf7
(ns boxing-the-compass (:use [clojure.string :only [capitalize]])) (def headings (for [i (range 0 (inc 32))] (let [heading (* i 11.25)] (case (mod i 3) 1 (+ heading 5.62) 2 (- heading 5.62) heading)))) (defn angle2compass [angle] (let [dirs ["N" "NbE" "N-NE" "NEbN" "NE" "NEbE" "E-NE" "EbN" "E" "EbS" "E-SE" "SEbE" "SE" "SEbS" "S-SE" "SbE" "S" "SbW" "S-SW" "SWbS" "SW" "SWbW" "W-SW" "WbS" "W" "WbN" "W-NW" "NWbW" "NW" "NWbN" "N-NW" "NbW"] unpack {\N "north" \E "east" \W "west" \S "south" \b " by " \- "-"} sep (/ 360 (count dirs)) dir (int (/ (mod (+ angle (/ sep 2)) 360) sep))] (capitalize (apply str (map unpack (dirs dir)))))) (print (apply str (map-indexed #(format "%2s%-18s%7.2f\n" (inc (mod %1 32)) (angle2compass %2) %2) headings)))
1,096Box the compass
6clojure
k1mhs
class Pixmap def histogram histogram = Hash.new(0) @height.times do |y| @width.times do |x| histogram[self[x,y].luminosity] += 1 end end histogram end def to_blackandwhite hist = histogram median = nil sum = 0 hist.keys.sort.each do |lum| sum += hist[lum] if sum > @height * @width / 2 median = lum break end end bw = self.class.new(@width, @height) @height.times do |y| @width.times do |x| bw[x,y] = self[x,y].luminosity < median? RGBColour::BLACK: RGBColour::WHITE end end bw end def save_as_blackandwhite(filename) to_blackandwhite.save(filename) end end Pixmap.open('file.ppm').save_as_blackandwhite('file_bw.ppm')
1,089Bitmap/Histogram
14ruby
t60f2
extern crate image; use image::{DynamicImage, GenericImageView, ImageBuffer, Rgba};
1,089Bitmap/Histogram
15rust
zy8to
Define cubic(p1,p2,p3,segs) = Prgm Local i,t,u,prev,pt 0 pt For i,1,segs+1 (i-1.0)/segs t Decimal to avoid slow exact arithetic (1-t) u pt prev u^2*p1 + 2*t*u*p2 + t^2*p3 pt If i>1 Then PxlLine floor(prev[1,1]), floor(prev[1,2]), floor(pt[1,1]), floor(pt[1,2]) EndIf EndFor EndPrgm
1,091Bitmap/Bézier curves/Quadratic
14ruby
od18v
null
1,092Bitmap/Midpoint circle algorithm
11kotlin
ugzvc
package raster const b3Seg = 30 func (b *Bitmap) Bzier3(x1, y1, x2, y2, x3, y3, x4, y4 int, p Pixel) { var px, py [b3Seg + 1]int fx1, fy1 := float64(x1), float64(y1) fx2, fy2 := float64(x2), float64(y2) fx3, fy3 := float64(x3), float64(y3) fx4, fy4 := float64(x4), float64(y4) for i := range px { d := float64(i) / b3Seg a := 1 - d b, c := a * a, d * d a, b, c, d = a*b, 3*b*d, 3*a*c, c*d px[i] = int(a*fx1 + b*fx2 + c*fx3 + d*fx4) py[i] = int(a*fy1 + b*fy2 + c*fy3 + d*fy4) } x0, y0 := px[0], py[0] for i := 1; i <= b3Seg; i++ { x1, y1 := px[i], py[i] b.Line(x0, y0, x1, y1, p) x0, y0 = x1, y1 } } func (b *Bitmap) Bzier3Rgb(x1, y1, x2, y2, x3, y3, x4, y4 int, c Rgb) { b.Bzier3(x1, y1, x2, y2, x3, y3, x4, y4, c.Pixel()) }
1,095Bitmap/Bézier curves/Cubic
0go
0i7sk
int day(int y, int m, int d) { return 367 * y - 7 * (y + (m + 9) / 12) / 4 + 275 * m / 9 + d - 730530; } void cycle(int diff, int l, char *t) { int p = round(100 * sin(2 * M_PI * diff / l)); printf(, t, p); if (abs(p) < 15) printf(); printf(); } int main(int argc, char *argv[]) { int diff; if (argc < 7) { printf(); printf(); exit(1); } diff = abs(day(atoi(argv[1]), atoi(argv[2]), atoi(argv[3])) - day(atoi(argv[4]), atoi(argv[5]), atoi(argv[6]))); printf(, diff); cycle(diff, 23, ); cycle(diff, 28, ); cycle(diff, 33, ); }
1,098Biorhythms
5c
ntji6
use Crypt::RIPEMD160; use Digest::SHA qw(sha256); use Encode::Base58::GMP; sub public_point_to_address { my $ec = join '', '04', @_; my $octets = pack 'C*', map { hex } unpack('(a2)65', $ec); my $hash = chr(0) . Crypt::RIPEMD160->hash(sha256 $octets); my $checksum = substr sha256(sha256 $hash), 0, 4; my $hex = join '', '0x', map { sprintf "%02X", $_ } unpack 'C*', $hash.$checksum; return '1' . sprintf "%32s", encode_base58($hex, 'bitcoin'); } say public_point_to_address '50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352', '2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6' ;
1,093Bitcoin/public point to address
2perl
lunc5
object BitmapOps { def histogram(bm:RgbBitmap)={ val hist=new Array[Int](255) for(x <- 0 until bm.width; y <- 0 until bm.height; l=luminosity(bm.getPixel(x,y))) hist(l)+=1 hist } def histogram_median(hist:Array[Int])={ var from=0 var to=hist.size-1 var left=hist(from) var right=hist(to) while(from!=to){ if (left<right) {from+=1; left+=hist(from)} else {to-=1; right+=hist(to)} } from } def monochrom(bm:RgbBitmap, threshold:Int)={ val image=new RgbBitmap(bm.width, bm.height) val c1=Color.BLACK val c2=Color.WHITE for(x <- 0 until bm.width; y <- 0 until bm.height; l=luminosity(bm.getPixel(x,y))) image.setPixel(x, y, if(l>threshold) c2 else c1) image } }
1,089Bitmap/Histogram
16scala
ycn63
function draw() { var canvas = document.getElementById("container"); context = canvas.getContext("2d"); bezier3(20, 200, 700, 50, -300, 50, 380, 150);
1,095Bitmap/Bézier curves/Cubic
10javascript
920ml
import 'package:crypto/crypto.dart'; class Bitcoin { final String ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; List<int> bigIntToByteArray(BigInt data) { String str; bool neg = false; if (data < BigInt.zero) { str = (~data).toRadixString(16); neg = true; } else str = data.toRadixString(16); int p = 0; int len = str.length; int blen = (len + 1) ~/ 2; int boff = 0; List bytes; if (neg) { if (len & 1 == 1) { p = -1; } int byte0 = ~int.parse(str.substring(0, p + 2), radix: 16); if (byte0 < -128) byte0 += 256; if (byte0 >= 0) { boff = 1; bytes = new List<int>(blen + 1); bytes[0] = -1; bytes[1] = byte0; } else { bytes = new List<int>(blen); bytes[0] = byte0; } for (int i = 1; i < blen; ++i) { int byte = ~int.parse(str.substring(p + (i << 1), p + (i << 1) + 2), radix: 16); if (byte < -128) byte += 256; bytes[i + boff] = byte; } } else { if (len & 1 == 1) { p = -1; } int byte0 = int.parse(str.substring(0, p + 2), radix: 16); if (byte0 > 127) byte0 -= 256; if (byte0 < 0) { boff = 1; bytes = new List<int>(blen + 1); bytes[0] = 0; bytes[1] = byte0; } else { bytes = new List<int>(blen); bytes[0] = byte0; } for (int i = 1; i < blen; ++i) { int byte = int.parse(str.substring(p + (i << 1), p + (i << 1) + 2), radix: 16); if (byte > 127) byte -= 256; bytes[i + boff] = byte; } } return bytes; } List<int> arrayCopy(bytes, srcOffset, result, destOffset, bytesLength) { for (int i = srcOffset; i < bytesLength; i++) { result[destOffset + i] = bytes[i]; } return result; } List<int> decodeBase58To25Bytes(String input) { BigInt number = BigInt.zero; for (String t in input.split('')) { int p = ALPHABET.indexOf(t); if (p == (-1)) return null; number = number * (BigInt.from(58)) + (BigInt.from(p)); } List<int> result = new List<int>(24); List<int> numBytes = bigIntToByteArray(number); return arrayCopy( numBytes, 0, result, result.length - numBytes.length, numBytes.length); } validateAddress(String address) { List<int> decoded = new List.from(decodeBase58To25Bytes(address)); List<int> temp = new List<int>.from(decoded); temp.insert(0, 0); List<int> hash1 = sha256.convert(temp.sublist(0, 21)).bytes; List<int> hash2 = sha256.convert(hash1).bytes; if (hash2[0]!= decoded[20] || hash2[1]!= decoded[21] || hash2[2]!= decoded[22] || hash2[3]!= decoded[23]) return false; return true; } }
1,097Bitcoin/address validation
18dart
69e34
use strict; use warnings; use Algorithm::Line::Bresenham 'circle'; my @points; my @circle = circle((10) x 3); for (@circle) { $points[$_->[0]][$_->[1]] = ' print join "\n", map { join '', map { $_ || ' ' } @$_ } @points
1,092Bitmap/Midpoint circle algorithm
2perl
8nb0w
null
1,095Bitmap/Bézier curves/Cubic
11kotlin
ifko4
import binascii import functools import hashlib digits58 = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' def b58(n): return b58(n def public_point_to_address(x, y): c = b'\x04' + binascii.unhexlify(x) + binascii.unhexlify(y) r = hashlib.new('ripemd160') r.update(hashlib.sha256(c).digest()) c = b'\x00' + r.digest() d = hashlib.sha256(hashlib.sha256(c).digest()).digest() return b58(functools.reduce(lambda n, b: n<<8|b, c + d[:4])) if __name__ == '__main__': print(public_point_to_address( b'50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352', b'2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6'))
1,093Bitcoin/public point to address
3python
25dlz
Bitmap.cubicbezier = function(self, x1, y1, x2, y2, x3, y3, x4, y4, nseg) nseg = nseg or 10 local prevx, prevy, currx, curry for i = 0, nseg do local t = i / nseg local a, b, c, d = (1-t)^3, 3*t*(1-t)^2, 3*t^2*(1-t), t^3 prevx, prevy = currx, curry currx = math.floor(a * x1 + b * x2 + c * x3 + d * x4 + 0.5) curry = math.floor(a * y1 + b * y2 + c * y3 + d * y4 + 0.5) if i > 0 then self:line(prevx, prevy, currx, curry) end end end local bitmap = Bitmap(61,21) bitmap:clear() bitmap:cubicbezier( 1,1, 15,41, 45,-20, 59,19 ) bitmap:render({[0x000000]='.', [0xFFFFFFFF]='X'})
1,095Bitmap/Bézier curves/Cubic
1lua
ntbi8
typedef struct genome{ char base; struct genome *next; }genome; typedef struct{ char mutation; int position; }genomeChange; typedef struct{ int adenineCount,thymineCount,cytosineCount,guanineCount; }baseCounts; genome *strand; baseCounts baseData; int genomeLength = 100, lineLength = 50; int numDigits(int num){ int len = 1; while(num>10){ num /= 10; len++; } return len; } void generateStrand(){ int baseChoice = rand()%4, i; genome *strandIterator, *newStrand; baseData.adenineCount = 0; baseData.thymineCount = 0; baseData.cytosineCount = 0; baseData.guanineCount = 0; strand = (genome*)malloc(sizeof(genome)); strand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G')); baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++)); strand->next = NULL; strandIterator = strand; for(i=1;i<genomeLength;i++){ baseChoice = rand()%4; newStrand = (genome*)malloc(sizeof(genome)); newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G')); baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++)); newStrand->next = NULL; strandIterator->next = newStrand; strandIterator = newStrand; } } genomeChange generateMutation(int swapWeight, int insertionWeight, int deletionWeight){ int mutationChoice = rand()%(swapWeight + insertionWeight + deletionWeight); genomeChange mutationCommand; mutationCommand.mutation = mutationChoice<swapWeight?'S':((mutationChoice>=swapWeight && mutationChoice<swapWeight+insertionWeight)?'I':'D'); mutationCommand.position = rand()%genomeLength; return mutationCommand; } void printGenome(){ int rows, width = numDigits(genomeLength), len = 0,i,j; lineLength = (genomeLength<lineLength)?genomeLength:lineLength; rows = genomeLength/lineLength + (genomeLength%lineLength!=0); genome* strandIterator = strand; printf(); for(i=0;i<rows;i++){ printf(,width,len,); for(j=0;j<lineLength && strandIterator!=NULL;j++){ printf(,strandIterator->base); strandIterator = strandIterator->next; } len += lineLength; } while(strandIterator!=NULL){ printf(,strandIterator->base); strandIterator = strandIterator->next; } printf(); printf(,width,'A',,width,baseData.adenineCount); printf(,width,'T',,width,baseData.thymineCount); printf(,width,'C',,width,baseData.cytosineCount); printf(,width,'G',,width,baseData.guanineCount); printf(,width,baseData.adenineCount + baseData.thymineCount + baseData.cytosineCount + baseData.guanineCount); printf(); } void mutateStrand(int numMutations, int swapWeight, int insertionWeight, int deletionWeight){ int i,j,width,baseChoice; genomeChange newMutation; genome *strandIterator, *strandFollower, *newStrand; for(i=0;i<numMutations;i++){ strandIterator = strand; strandFollower = strand; newMutation = generateMutation(swapWeight,insertionWeight,deletionWeight); width = numDigits(genomeLength); for(j=0;j<newMutation.position;j++){ strandFollower = strandIterator; strandIterator = strandIterator->next; } if(newMutation.mutation=='S'){ if(strandIterator->base=='A'){ strandIterator->base='T'; printf(,width,newMutation.position); } else if(strandIterator->base=='A'){ strandIterator->base='T'; printf(,width,newMutation.position); } else if(strandIterator->base=='C'){ strandIterator->base='G'; printf(,width,newMutation.position); } else{ strandIterator->base='C'; printf(,width,newMutation.position); } } else if(newMutation.mutation=='I'){ baseChoice = rand()%4; newStrand = (genome*)malloc(sizeof(genome)); newStrand->base = baseChoice==0?'A':(baseChoice==1?'T':(baseChoice==2?'C':'G')); printf(,newStrand->base,width,newMutation.position); baseChoice==0?baseData.adenineCount++:(baseChoice==1?baseData.thymineCount++:(baseChoice==2?baseData.cytosineCount++:baseData.guanineCount++)); newStrand->next = strandIterator; strandFollower->next = newStrand; genomeLength++; } else{ strandFollower->next = strandIterator->next; strandIterator->next = NULL; printf(,strandIterator->base,width,newMutation.position); free(strandIterator); genomeLength--; } } } int main(int argc,char* argv[]) { int numMutations = 10, swapWeight = 10, insertWeight = 10, deleteWeight = 10; if(argc==1||argc>6){ printf(,argv[0]); return 0; } switch(argc){ case 2: genomeLength = atoi(argv[1]); break; case 3: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); break; case 4: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); swapWeight = atoi(argv[3]); break; case 5: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); swapWeight = atoi(argv[3]); insertWeight = atoi(argv[4]); break; case 6: genomeLength = atoi(argv[1]); numMutations = atoi(argv[2]); swapWeight = atoi(argv[3]); insertWeight = atoi(argv[4]); deleteWeight = atoi(argv[5]); break; }; srand(time(NULL)); generateStrand(); printf(); printGenome(); mutateStrand(numMutations,swapWeight,insertWeight,deleteWeight); printf(); printGenome(); return 0; }
1,099Bioinformatics/Sequence mutation
5c
jbt70
function line { x0=$1 y0=$2 x1=$3 y1=$4 if (( x0 > x1 )) then (( dx = x0 - x1 )) (( sx = -1 )) else (( dx = x1 - x0 )) (( sx = 1 )) fi if (( y0 > y1 )) then (( dy = y0 - y1 )) (( sy = -1 )) else (( dy = y1 - y0 )) (( sy = 1 )) fi if (( dx > dy )) then (( err = dx )) else (( err = -dy )) fi (( err /= 2 )) (( e2 = 0 )) while: do echo -en "\e[${y0};${x0}H (( x0 == x1 && y0 == y1 )) && return (( e2 = err )) if (( e2 > -dx )) then (( err -= dy )) (( x0 += sx )) fi if (( e2 < dy )) then (( err += dx )) (( y0 += sy )) fi done } COLS=$( tput cols ) LINS=$( tput lines ) LINS=$((LINS-1)) clear line $((COLS/2)) 1 $((COLS/4)) $((LINS/2)) line $((COLS/4)) $((LINS/2)) $((COLS/2)) $LINS line $((COLS/2)) $LINS $((COLS/4*3)) $((LINS/2)) line $((COLS/4*3)) $((LINS/2)) $((COLS/2)) 1 echo -e "\e[${LINS}H"
1,100Bitmap/Bresenham's line algorithm
4bash
pe6bb
package main import ( "bytes" "crypto/sha256" "errors" "os" )
1,097Bitcoin/address validation
0go
q85xz
require 'digest/sha2' def convert g i,e = '',[] (0...g.length/2).each{|n| e[n] = g[n+=n]+g[n+1]; i+='H2'} e.pack(i) end X = '50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352' Y = '2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6' n = '00'+Digest::RMD160.hexdigest(Digest::SHA256.digest(convert('04'+X+Y))) n+= Digest::SHA256.hexdigest(Digest::SHA256.digest(convert(n)))[0,8] G = n,res = n.hex,'' while n > 0 do n,ng = n.divmod(58) res << G[ng] end puts res.reverse
1,093Bitcoin/public point to address
14ruby
ugtvz
use ring::digest::{digest, SHA256}; use ripemd160::{Digest, Ripemd160}; use hex::FromHex; static X: &str = "50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352"; static Y: &str = "2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6"; static ALPHABET: [char; 58] = [ '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ]; fn base58_encode(bytes: &mut [u8]) -> String { let base = ALPHABET.len(); if bytes.is_empty() { return String::from(""); } let mut output: Vec<u8> = Vec::new(); let mut num: usize; for _ in 0..33 { num = 0; for byte in bytes.iter_mut() { num = num * 256 + *byte as usize; *byte = (num / base) as u8; num%= base; } output.push(num as u8); } let mut string = String::new(); for b in output.iter().rev() { string.push(ALPHABET[*b as usize]); } string }
1,093Bitcoin/public point to address
15rust
5rzuq
def circle(self, x0, y0, radius, colour=black): f = 1 - radius ddf_x = 1 ddf_y = -2 * radius x = 0 y = radius self.set(x0, y0 + radius, colour) self.set(x0, y0 - radius, colour) self.set(x0 + radius, y0, colour) self.set(x0 - radius, y0, colour) while x < y: if f >= 0: y -= 1 ddf_y += 2 f += ddf_y x += 1 ddf_x += 2 f += ddf_x self.set(x0 + x, y0 + y, colour) self.set(x0 - x, y0 + y, colour) self.set(x0 + x, y0 - y, colour) self.set(x0 - x, y0 - y, colour) self.set(x0 + y, y0 + x, colour) self.set(x0 - y, y0 + x, colour) self.set(x0 + y, y0 - x, colour) self.set(x0 - y, y0 - x, colour) Bitmap.circle = circle bitmap = Bitmap(25,25) bitmap.circle(x0=12, y0=12, radius=12) bitmap.chardisplay() ''' The origin, 0,0; is the lower left, with x increasing to the right, and Y increasing upwards. The program above produces the following display: +-------------------------+ | @@@@@@@ | | @@ @@ | | @@ @@ | | @ @ | | @ @ | | @ @ | | @ @ | | @ @ | | @ @ | |@ @| |@ @| |@ @| |@ @| |@ @| |@ @| |@ @| | @ @ | | @ @ | | @ @ | | @ @ | | @ @ | | @ @ | | @@ @@ | | @@ @@ | | @@@@@@@ | +-------------------------+ '''
1,092Bitmap/Midpoint circle algorithm
3python
odp81
package main import ( "fmt" "log" "math" "time" ) const layout = "2006-01-02"
1,098Biorhythms
0go
rhfgm
import Control.Monad (when) import Data.List (elemIndex) import Data.Monoid ((<>)) import qualified Data.ByteString as BS import Data.ByteString (ByteString) import Crypto.Hash.SHA256 (hash) decode58 :: String -> Maybe Integer decode58 = fmap combine . traverse parseDigit where combine = foldl (\acc digit -> 58 * acc + digit) 0 parseDigit char = toInteger <$> elemIndex char c58 c58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" toBytes :: Integer -> ByteString toBytes = BS.reverse . BS.pack . map (fromIntegral . (`mod` 256)) . takeWhile (> 0) . iterate (`div` 256) checksumValid :: ByteString -> Bool checksumValid address = let (value, checksum) = BS.splitAt 21 $ leftPad address in and $ BS.zipWith (==) checksum $ hash $ hash $ value where leftPad bs = BS.replicate (25 - BS.length bs) 0 <> bs withError :: e -> Maybe a -> Either e a withError e = maybe (Left e) Right validityCheck :: String -> Either String () validityCheck encoded = do num <- withError "Invalid base 58 encoding" $ decode58 encoded let address = toBytes num when (BS.length address > 25) $ Left "Address length exceeds 25 bytes" when (BS.length address < 4) $ Left "Address length less than 4 bytes" when (not $ checksumValid address) $ Left "Invalid checksum" validate :: String -> IO () validate encodedAddress = do let result = either show (const "Valid") $ validityCheck encodedAddress putStrLn $ show encodedAddress ++ " -> " ++ result main :: IO () main = do validate "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i" validate "1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9" validate "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62X" validate "1ANNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i" validate "1A Na15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i" validate "1ANa55215ZQXAZUgFiqJ2i7Z2DPU2J6hW62i" validate "i55j"
1,097Bitcoin/address validation
8haskell
mlxyf
package raster func (b *Bitmap) Flood(x, y int, repl Pixel) { targ, _ := b.GetPx(x, y) var ff func(x, y int) ff = func(x, y int) { p, ok := b.GetPx(x, y) if ok && p.R == targ.R && p.G == targ.G && p.B == targ.B { b.SetPx(x, y, repl) ff(x-1, y) ff(x+1, y) ff(x, y-1) ff(x, y+1) } } ff(x, y) }
1,094Bitmap/Flood fill
0go
so7qa
package main import ( "fmt" "math/rand" "sort" "time" ) const bases = "ACGT"
1,099Bioinformatics/Sequence mutation
0go
f3hd0
import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; public class BitcoinAddressValidator { private static final String ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; public static boolean validateBitcoinAddress(String addr) { if (addr.length() < 26 || addr.length() > 35) return false; byte[] decoded = decodeBase58To25Bytes(addr); if (decoded == null) return false; byte[] hash1 = sha256(Arrays.copyOfRange(decoded, 0, 21)); byte[] hash2 = sha256(hash1); return Arrays.equals(Arrays.copyOfRange(hash2, 0, 4), Arrays.copyOfRange(decoded, 21, 25)); } private static byte[] decodeBase58To25Bytes(String input) { BigInteger num = BigInteger.ZERO; for (char t : input.toCharArray()) { int p = ALPHABET.indexOf(t); if (p == -1) return null; num = num.multiply(BigInteger.valueOf(58)).add(BigInteger.valueOf(p)); } byte[] result = new byte[25]; byte[] numBytes = num.toByteArray(); System.arraycopy(numBytes, 0, result, result.length - numBytes.length, numBytes.length); return result; } private static byte[] sha256(byte[] data) { try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(data); return md.digest(); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); } } public static void main(String[] args) { assertBitcoin("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", true); assertBitcoin("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62j", false); assertBitcoin("1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9", true); assertBitcoin("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62X", false); assertBitcoin("1ANNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", false); assertBitcoin("1A Na15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", false); assertBitcoin("BZbvjr", false); assertBitcoin("i55j", false); assertBitcoin("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62!", false); assertBitcoin("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62iz", false); assertBitcoin("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62izz", false); assertBitcoin("1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nJ9", false); assertBitcoin("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62I", false); } private static void assertBitcoin(String address, boolean expected) { boolean actual = validateBitcoinAddress(address); if (actual != expected) throw new AssertionError(String.format("Expected%s for%s, but got%s.", expected, address, actual)); } }
1,097Bitcoin/address validation
9java
f3bdv
import Data.Array.ST import Data.STRef import Control.Monad import Control.Monad.ST import Bitmap pushST :: STStack s a -> a -> ST s () pushST s e = do s2 <- readSTRef s writeSTRef s (e: s2) popST :: STStack s a -> ST s (Stack a) popST s = do s2 <- readSTRef s writeSTRef s $ tail s2 return $ take 1 s2 isNotEmptySTStack :: STStack s a -> ST s Bool isNotEmptySTStack s = do s2 <- readSTRef s return $ not $ null s2 emptySTStack :: ST s (STStack s a) emptySTStack = newSTRef [] consumeSTStack :: STStack s a -> (a -> ST s ()) -> ST s () consumeSTStack s f = do check <- isNotEmptySTStack s when check $ do e <- popST s f $ head e consumeSTStack s f type Spanning s = STRef s (Bool, Bool) setSpanLeft :: Spanning s -> Bool -> ST s () setSpanLeft s v = do (_, r) <- readSTRef s writeSTRef s (v, r) setSpanRight :: Spanning s -> Bool -> ST s () setSpanRight s v = do (l, _) <- readSTRef s writeSTRef s (l, v) setSpanNone :: Spanning s -> ST s () setSpanNone s = writeSTRef s (False, False) floodFillScanlineStack :: Color c => Image s c -> Pixel -> c -> ST s (Image s c) floodFillScanlineStack b coords newC = do stack <- emptySTStack spans <- newSTRef (False, False) fFSS b stack coords newC spans return b where fFSS b st c newC p = do oldC <- getPix b c unless (oldC == newC) $ do pushST st c (w, h) <- dimensions b consumeSTStack st (scanWhileY b p oldC >=> scanWhileX b st p oldC newC (w, h)) scanWhileY b p oldC coords@(Pixel (x, y)) = if y >= 0 then do z <- getPix b coords if z == oldC then scanWhileY b p oldC (Pixel (x, y - 1)) else do setSpanNone p return (Pixel (x, y + 1)) else do setSpanNone p return (Pixel (x, y + 1)) scanWhileX b st p oldC newC (w, h) coords@(Pixel (x, y)) = when (y < h) $ do z <- getPix b coords when (z == oldC) $ do setPix b coords newC (spanLeft, spanRight) <- readSTRef p when (not spanLeft && x > 0) $ do z2 <- getPix b (Pixel (x - 1, y)) when (z2 == oldC) $ do pushST st (Pixel (x - 1, y)) setSpanLeft p True when (spanLeft && x > 0) $ do z3 <- getPix b (Pixel (x - 1, y)) when (z3 /= oldC) $ setSpanLeft p False when (not spanRight && x < (w - 1)) $ do z4 <- getPix b (Pixel (x + 1, y)) when (z4 == oldC) $ do pushST st (Pixel (x + 1, y)) setSpanRight p True when (spanRight && x < (w - 1)) $ do z5 <- getPix b (Pixel (x + 1, y)) when (z5 /= oldC) $ setSpanRight p False scanWhileX b st p oldC newC (w, h) (Pixel (x, y + 1))
1,094Bitmap/Flood fill
8haskell
928mo
package main import ( "fmt" "reflect" "strconv" ) func main() { var n bool = true fmt.Println(n)
1,090Boolean values
0go
7klr2
<? $image = imagecreate(200, 200); imagecolorallocate($image, 255, 255, 255); $color = imagecolorallocate($image, 255, 0, 0); cubicbezier($image, $color, 160, 10, 10, 40, 30, 160, 150, 110); imagepng($image); function cubicbezier($img, $col, $x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $n = 20) { $pts = array(); for($i = 0; $i <= $n; $i++) { $t = $i / $n; $t1 = 1 - $t; $a = pow($t1, 3); $b = 3 * $t * pow($t1, 2); $c = 3 * pow($t, 2) * $t1; $d = pow($t, 3); $x = round($a * $x0 + $b * $x1 + $c * $x2 + $d * $x3); $y = round($a * $y0 + $b * $y1 + $c * $y2 + $d * $y3); $pts[$i] = array($x, $y); } for($i = 0; $i < $n; $i++) { imageline($img, $pts[$i][0], $pts[$i][1], $pts[$i+1][0], $pts[$i+1][1], $col); } }
1,095Bitmap/Bézier curves/Cubic
12php
dzpn8
import Data.List (group, sort) import Data.List.Split (chunksOf) import System.Random (Random, randomR, random, newStdGen, randoms, getStdRandom) import Text.Printf (PrintfArg(..), fmtChar, fmtPrecision, formatString, IsChar(..), printf) data Mutation = Swap | Delete | Insert deriving (Show, Eq, Ord, Enum, Bounded) data DNABase = A | C | G | T deriving (Show, Read, Eq, Ord, Enum, Bounded) type DNASequence = [DNABase] data Result = Swapped Mutation Int (DNABase, DNABase) | InsertDeleted Mutation Int DNABase instance Random DNABase where randomR (a, b) g = case randomR (fromEnum a, fromEnum b) g of (x, y) -> (toEnum x, y) random = randomR (minBound, maxBound) instance Random Mutation where randomR (a, b) g = case randomR (fromEnum a, fromEnum b) g of (x, y) -> (toEnum x, y) random = randomR (minBound, maxBound) instance PrintfArg DNABase where formatArg x fmt = formatString (show x) (fmt { fmtChar = 's', fmtPrecision = Nothing }) instance PrintfArg Mutation where formatArg x fmt = formatString (show x) (fmt { fmtChar = 's', fmtPrecision = Nothing }) instance IsChar DNABase where toChar = head . show fromChar = read . pure chunkedDNASequence :: DNASequence -> [(Int, [DNABase])] chunkedDNASequence = zip [50,100..] . chunksOf 50 baseCounts :: DNASequence -> [(DNABase, Int)] baseCounts = fmap ((,) . head <*> length) . group . sort newSequence :: Int -> IO DNASequence newSequence n = take n . randoms <$> newStdGen mutateSequence :: DNASequence -> IO (Result, DNASequence) mutateSequence [] = fail "empty dna sequence" mutateSequence ds = randomMutation >>= mutate ds where randomMutation = head . randoms <$> newStdGen mutate xs m = do i <- randomIndex (length xs) case m of Swap -> randomDNA >>= \d -> pure (Swapped Swap i (xs !! pred i, d), swapElement i d xs) Insert -> randomDNA >>= \d -> pure (InsertDeleted Insert i d, insertElement i d xs) Delete -> pure (InsertDeleted Delete i (xs !! pred i), dropElement i xs) where dropElement i xs = take (pred i) xs <> drop i xs insertElement i e xs = take i xs <> [e] <> drop i xs swapElement i a xs = take (pred i) xs <> [a] <> drop i xs randomIndex n = getStdRandom (randomR (1, n)) randomDNA = head . randoms <$> newStdGen mutate :: Int -> DNASequence -> IO DNASequence mutate 0 s = pure s mutate n s = do (r, ms) <- mutateSequence s case r of Swapped m i (a, b) -> printf "%6s @%-3d:%s ->%s \n" m i a b InsertDeleted m i a -> printf "%6s @%-3d:%s\n" m i a mutate (pred n) ms main :: IO () main = do ds <- newSequence 200 putStrLn "\nInitial Sequence:" >> showSequence ds putStrLn "\nBase Counts:" >> showBaseCounts ds showSumBaseCounts ds ms <- mutate 10 ds putStrLn "\nMutated Sequence:" >> showSequence ms putStrLn "\nBase Counts:" >> showBaseCounts ms showSumBaseCounts ms where showSequence = mapM_ (uncurry (printf "%3d:%s\n")) . chunkedDNASequence showBaseCounts = mapM_ (uncurry (printf "%s:%3d\n")) . baseCounts showSumBaseCounts xs = putStrLn (replicate 6 '-') >> printf ":%d\n\n" (length xs)
1,099Bioinformatics/Sequence mutation
8haskell
47i5s
import java.security.MessageDigest object Bitcoin { private const val ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" private fun ByteArray.contentEquals(other: ByteArray): Boolean { if (this.size != other.size) return false return (0 until this.size).none { this[it] != other[it] } } private fun decodeBase58(input: String): ByteArray? { val output = ByteArray(25) for (c in input) { var p = ALPHABET.indexOf(c) if (p == -1) return null for (j in 24 downTo 1) { p += 58 * (output[j].toInt() and 0xff) output[j] = (p % 256).toByte() p = p shr 8 } if (p != 0) return null } return output } private fun sha256(data: ByteArray, start: Int, len: Int, recursion: Int): ByteArray { if (recursion == 0) return data val md = MessageDigest.getInstance("SHA-256") md.update(data.sliceArray(start until start + len)) return sha256(md.digest(), 0, 32, recursion - 1) } fun validateAddress(address: String): Boolean { if (address.length !in 26..35) return false val decoded = decodeBase58(address) if (decoded == null) return false val hash = sha256(decoded, 0, 21, 2) return hash.sliceArray(0..3).contentEquals(decoded.sliceArray(21..24)) } } fun main(args: Array<String>) { val addresses = arrayOf( "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62j", "1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9", "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62X", "1ANNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", "1A Na15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", "BZbvjr", "i55j", "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62!", "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62iz", "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62izz", "1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nJ9", "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62I" ) for (address in addresses) println("${address.padEnd(36)} -> ${if (Bitcoin.validateAddress(address)) "valid" else "invalid"}") }
1,097Bitcoin/address validation
11kotlin
8nr0q
data Bool = False | True deriving (Eq, Ord, Enum, Read, Show, Bounded)
1,090Boolean values
7groovy
ug6v9
data Bool = False | True deriving (Eq, Ord, Enum, Read, Show, Bounded)
1,090Boolean values
8haskell
8n10z
cycles = {"Physical day ", "Emotional day", "Mental day "} lengths = {23, 28, 33} quadrants = { {"up and rising", "peak"}, {"up but falling", "transition"}, {"down and falling", "valley"}, {"down but rising", "transition"}, } function parse_date_string (birthDate) local year, month, day = birthDate:match("(%d+)-(%d+)-(%d+)") return {year=tonumber(year), month=tonumber(month), day=tonumber(day)} end function days_diffeternce (d1, d2) if d1.year >= 1970 and d2.year >= 1970 then return math.floor(os.difftime(os.time(d2), os.time(d1))/(60*60*24)) else local t1 = math.max (1970-d1.year, 1970-d2.year) t1 = math.ceil(t1/4)*4 d1.year = d1.year + t1 d2.year = d2.year + t1 return math.floor(os.difftime(os.time(d2), os.time(d1))/(60*60*24)) end end function biorhythms (birthDate, targetDate) local bd = parse_date_string(birthDate) local td = parse_date_string(targetDate) local days = days_diffeternce (bd, td) print('Born: '.. birthDate .. ', Target: ' .. targetDate) print("Day: ", days) for i=1, #lengths do local len = lengths[i] local posn = days%len local quadrant = math.floor(posn/len*4)+1 local percent = math.floor(math.sin(2*math.pi*posn/len)*1000)/10 local cycle = cycles[i] local desc = percent > 95 and "peak" or percent < -95 and "valley" or math.abs(percent) < 5 and "critical transition" or "other" if desc == "other" then local t = math.floor(quadrant/4*len)-posn local qtrend, qnext = quadrants[quadrant][1], quadrants[quadrant][2] desc = percent .. '% (' .. qtrend .. ', next transition in ' .. t ..' days)' end print(cycle, posn..'/'..len, ': '.. desc) end print(' ') end datePairs = { {"1943-03-09", "1972-07-11"}, {"1809-01-12", "1863-11-19"}, {"1809-02-12", "1863-11-19"}, {"2021-02-25", "2022-04-18"}, } for i=1, #datePairs do biorhythms(datePairs[i][1], datePairs[i][2]) end
1,098Biorhythms
1lua
k16h2
typedef struct genome{ char* strand; int length; struct genome* next; }genome; genome* genomeData; int totalLength = 0, Adenine = 0, Cytosine = 0, Guanine = 0, Thymine = 0; int numDigits(int num){ int len = 1; while(num>10){ num = num/10; len++; } return len; } void buildGenome(char str[100]){ int len = strlen(str),i; genome *genomeIterator, *newGenome; totalLength += len; for(i=0;i<len;i++){ switch(str[i]){ case 'A': Adenine++; break; case 'T': Thymine++; break; case 'C': Cytosine++; break; case 'G': Guanine++; break; }; } if(genomeData==NULL){ genomeData = (genome*)malloc(sizeof(genome)); genomeData->strand = (char*)malloc(len*sizeof(char)); strcpy(genomeData->strand,str); genomeData->length = len; genomeData->next = NULL; } else{ genomeIterator = genomeData; while(genomeIterator->next!=NULL) genomeIterator = genomeIterator->next; newGenome = (genome*)malloc(sizeof(genome)); newGenome->strand = (char*)malloc(len*sizeof(char)); strcpy(newGenome->strand,str); newGenome->length = len; newGenome->next = NULL; genomeIterator->next = newGenome; } } void printGenome(){ genome* genomeIterator = genomeData; int width = numDigits(totalLength), len = 0; printf(); while(genomeIterator!=NULL){ printf(,width+1,len,,genomeIterator->strand); len += genomeIterator->length; genomeIterator = genomeIterator->next; } printf(); printf(,'A',,width+1,Adenine); printf(,'T',,width+1,Thymine); printf(,'C',,width+1,Cytosine); printf(,'G',,width+1,Guanine); printf(,,width+1,Adenine + Thymine + Cytosine + Guanine); free(genomeData); } int main(int argc,char** argv) { char str[100]; int counter = 0, len; if(argc!=2){ printf(,argv[0]); return 0; } FILE *fp = fopen(argv[1],); while(fscanf(fp,,str)!=EOF) buildGenome(str); fclose(fp); printGenome(); return 0; }
1,101Bioinformatics/base count
5c
if4o2
void line(int x0, int y0, int x1, int y1) { int dx = abs(x1-x0), sx = x0<x1 ? 1 : -1; int dy = abs(y1-y0), sy = y0<y1 ? 1 : -1; int err = (dx>dy ? dx : -dy)/2, e2; for(;;){ setPixel(x0,y0); if (x0==x1 && y0==y1) break; e2 = err; if (e2 >-dx) { err -= dy; x0 += sx; } if (e2 < dy) { err += dx; y0 += sy; } } }
1,100Bitmap/Bresenham's line algorithm
5c
axm11
import java.awt.Color; import java.awt.Point; import java.awt.image.BufferedImage; import java.util.Deque; import java.util.LinkedList; public class FloodFill { public void floodFill(BufferedImage image, Point node, Color targetColor, Color replacementColor) { int width = image.getWidth(); int height = image.getHeight(); int target = targetColor.getRGB(); int replacement = replacementColor.getRGB(); if (target != replacement) { Deque<Point> queue = new LinkedList<Point>(); do { int x = node.x; int y = node.y; while (x > 0 && image.getRGB(x - 1, y) == target) { x--; } boolean spanUp = false; boolean spanDown = false; while (x < width && image.getRGB(x, y) == target) { image.setRGB(x, y, replacement); if (!spanUp && y > 0 && image.getRGB(x, y - 1) == target) { queue.add(new Point(x, y - 1)); spanUp = true; } else if (spanUp && y > 0 && image.getRGB(x, y - 1) != target) { spanUp = false; } if (!spanDown && y < height - 1 && image.getRGB(x, y + 1) == target) { queue.add(new Point(x, y + 1)); spanDown = true; } else if (spanDown && y < height - 1 && image.getRGB(x, y + 1) != target) { spanDown = false; } x++; } } while ((node = queue.pollFirst()) != null); } } }
1,094Bitmap/Flood fill
9java
t6ef9
Pixel = Struct.new(:x, :y) class Pixmap def draw_circle(pixel, radius, colour) validate_pixel(pixel.x, pixel.y) self[pixel.x, pixel.y + radius] = colour self[pixel.x, pixel.y - radius] = colour self[pixel.x + radius, pixel.y] = colour self[pixel.x - radius, pixel.y] = colour f = 1 - radius ddF_x = 1 ddF_y = -2 * radius x = 0 y = radius while x < y if f >= 0 y -= 1 ddF_y += 2 f += ddF_y end x += 1 ddF_x += 2 f += ddF_x self[pixel.x + x, pixel.y + y] = colour self[pixel.x + x, pixel.y - y] = colour self[pixel.x - x, pixel.y + y] = colour self[pixel.x - x, pixel.y - y] = colour self[pixel.x + y, pixel.y + x] = colour self[pixel.x + y, pixel.y - x] = colour self[pixel.x - y, pixel.y + x] = colour self[pixel.x - y, pixel.y - x] = colour end end end bitmap = Pixmap.new(30, 30) bitmap.draw_circle(Pixel[14,14], 12, RGBColour::BLACK)
1,092Bitmap/Midpoint circle algorithm
14ruby
ntait
def cubicbezier(self, x0, y0, x1, y1, x2, y2, x3, y3, n=20): pts = [] for i in range(n+1): t = i / n a = (1. - t)**3 b = 3. * t * (1. - t)**2 c = 3.0 * t**2 * (1.0 - t) d = t**3 x = int(a * x0 + b * x1 + c * x2 + d * x3) y = int(a * y0 + b * y1 + c * y2 + d * y3) pts.append( (x, y) ) for i in range(n): self.line(pts[i][0], pts[i][1], pts[i+1][0], pts[i+1][1]) Bitmap.cubicbezier = cubicbezier bitmap = Bitmap(17,17) bitmap.cubicbezier(16,1, 1,4, 3,16, 15,11) bitmap.chardisplay() ''' The origin, 0,0; is the lower left, with x increasing to the right, and Y increasing upwards. The chardisplay above produces the following output: +-----------------+ | | | | | | | | | @@@@ | | @@@ @@@ | | @ | | @ | | @ | | @ | | @ | | @ | | @ | | @ | | @@@@ | | @@@@| | | +-----------------+ '''
1,095Bitmap/Bézier curves/Cubic
3python
7k6rm
bezierCurve <- function(x, y, n=10) { outx <- NULL outy <- NULL i <- 1 for (t in seq(0, 1, length.out=n)) { b <- bez(x, y, t) outx[i] <- b$x outy[i] <- b$y i <- i+1 } return (list(x=outx, y=outy)) } bez <- function(x, y, t) { outx <- 0 outy <- 0 n <- length(x)-1 for (i in 0:n) { outx <- outx + choose(n, i)*((1-t)^(n-i))*t^i*x[i+1] outy <- outy + choose(n, i)*((1-t)^(n-i))*t^i*y[i+1] } return (list(x=outx, y=outy)) } x <- c(4,6,4,5,6,7) y <- 1:6 plot(x, y, "o", pch=20) points(bezierCurve(x,y,20), type="l", col="red")
1,095Bitmap/Bézier curves/Cubic
13r
5rfuy
use strict; use warnings; use DateTime; use constant PI => 2 * atan2(1, 0); my %cycles = ( 'Physical' => 23, 'Emotional' => 28, 'Mental' => 33 ); my @Q = ( ['up and rising', 'peak'], ['up but falling', 'transition'], ['down and falling', 'valley'], ['down but rising', 'transition'] ); my $target = DateTime->new(year=>1863, month=>11, day=>19); my $bday = DateTime->new(year=>1809, month=> 2, day=>12); my $days = $bday->delta_days( $target )->in_units('days'); print "Day $days:\n"; for my $label (sort keys %cycles) { my($length) = $cycles{$label}; my $position = $days % $length; my $quadrant = int $position / $length * 4; my $percentage = int(sin($position / $length * 2 * PI )*1000)/10; my $description; if ( $percentage > 95) { $description = 'peak' } elsif ( $percentage < -95) { $description = 'valley' } elsif (abs($percentage) < 5) { $description = 'critical transition' } else { my $transition = $target->clone->add( days => (int(($quadrant + 1)/4 * $length) - $position))->ymd; my ($trend, $next) = @{$Q[$quadrant]}; $description = sprintf "%5.1f%% ($trend, next $next $transition)", $percentage; } printf "%-13s%2d:%s", "$label day\n", $position, $description; }
1,098Biorhythms
2perl
zyptb
import java.util.Arrays; import java.util.Random; public class SequenceMutation { public static void main(String[] args) { SequenceMutation sm = new SequenceMutation(); sm.setWeight(OP_CHANGE, 3); String sequence = sm.generateSequence(250); System.out.println("Initial sequence:"); printSequence(sequence); int count = 10; for (int i = 0; i < count; ++i) sequence = sm.mutateSequence(sequence); System.out.println("After " + count + " mutations:"); printSequence(sequence); } public SequenceMutation() { totalWeight_ = OP_COUNT; Arrays.fill(operationWeight_, 1); } public String generateSequence(int length) { char[] ch = new char[length]; for (int i = 0; i < length; ++i) ch[i] = getRandomBase(); return new String(ch); } public void setWeight(int operation, int weight) { totalWeight_ -= operationWeight_[operation]; operationWeight_[operation] = weight; totalWeight_ += weight; } public String mutateSequence(String sequence) { char[] ch = sequence.toCharArray(); int pos = random_.nextInt(ch.length); int operation = getRandomOperation(); if (operation == OP_CHANGE) { char b = getRandomBase(); System.out.println("Change base at position " + pos + " from " + ch[pos] + " to " + b); ch[pos] = b; } else if (operation == OP_ERASE) { System.out.println("Erase base " + ch[pos] + " at position " + pos); char[] newCh = new char[ch.length - 1]; System.arraycopy(ch, 0, newCh, 0, pos); System.arraycopy(ch, pos + 1, newCh, pos, ch.length - pos - 1); ch = newCh; } else if (operation == OP_INSERT) { char b = getRandomBase(); System.out.println("Insert base " + b + " at position " + pos); char[] newCh = new char[ch.length + 1]; System.arraycopy(ch, 0, newCh, 0, pos); System.arraycopy(ch, pos, newCh, pos + 1, ch.length - pos); newCh[pos] = b; ch = newCh; } return new String(ch); } public static void printSequence(String sequence) { int[] count = new int[BASES.length]; for (int i = 0, n = sequence.length(); i < n; ++i) { if (i % 50 == 0) { if (i != 0) System.out.println(); System.out.printf("%3d: ", i); } char ch = sequence.charAt(i); System.out.print(ch); for (int j = 0; j < BASES.length; ++j) { if (BASES[j] == ch) { ++count[j]; break; } } } System.out.println(); System.out.println("Base counts:"); int total = 0; for (int j = 0; j < BASES.length; ++j) { total += count[j]; System.out.print(BASES[j] + ": " + count[j] + ", "); } System.out.println("Total: " + total); } private char getRandomBase() { return BASES[random_.nextInt(BASES.length)]; } private int getRandomOperation() { int n = random_.nextInt(totalWeight_), op = 0; for (int weight = 0; op < OP_COUNT; ++op) { weight += operationWeight_[op]; if (n < weight) break; } return op; } private final Random random_ = new Random(); private int[] operationWeight_ = new int[OP_COUNT]; private int totalWeight_ = 0; private static final int OP_CHANGE = 0; private static final int OP_ERASE = 1; private static final int OP_INSERT = 2; private static final int OP_COUNT = 3; private static final char[] BASES = {'A', 'C', 'G', 'T'}; }
1,099Bioinformatics/Sequence mutation
9java
cvx9h
null
1,094Bitmap/Flood fill
11kotlin
odk8z
object BitmapOps { def midpoint(bm:RgbBitmap, x0:Int, y0:Int, radius:Int, c:Color)={ var f=1-radius var ddF_x=1 var ddF_y= -2*radius var x=0 var y=radius bm.setPixel(x0, y0+radius, c) bm.setPixel(x0, y0-radius, c) bm.setPixel(x0+radius, y0, c) bm.setPixel(x0-radius, y0, c) while(x < y) { if(f >= 0) { y-=1 ddF_y+=2 f+=ddF_y } x+=1 ddF_x+=2 f+=ddF_x bm.setPixel(x0+x, y0+y, c) bm.setPixel(x0-x, y0+y, c) bm.setPixel(x0+x, y0-y, c) bm.setPixel(x0-x, y0-y, c) bm.setPixel(x0+y, y0+x, c) bm.setPixel(x0-y, y0+x, c) bm.setPixel(x0+y, y0-x, c) bm.setPixel(x0-y, y0-x, c) } } }
1,092Bitmap/Midpoint circle algorithm
16scala
zyqtr
null
1,099Bioinformatics/Sequence mutation
10javascript
5rour
my @b58 = qw{ 1 2 3 4 5 6 7 8 9 A B C D E F G H J K L M N P Q R S T U V W X Y Z a b c d e f g h i j k m n o p q r s t u v w x y z }; my %b58 = map { $b58[$_] => $_ } 0 .. 57; sub unbase58 { use integer; my @out; my $azeroes = length($1) if $_[0] =~ /^(1*)/; for my $c ( map { $b58{$_} } $_[0] =~ /./g ) { for (my $j = 25; $j--; ) { $c += 58 * ($out[$j] // 0); $out[$j] = $c % 256; $c /= 256; } } my $bzeroes = length($1) if join('', @out) =~ /^(0*)/; die "not a 25 byte address\n" if $bzeroes != $azeroes; return @out; } sub check_bitcoin_address { use Digest::SHA qw(sha256); my @byte = unbase58 shift; die "wrong checksum\n" unless (pack 'C*', @byte[21..24]) eq substr sha256(sha256 pack 'C*', @byte[0..20]), 0, 4; }
1,097Bitcoin/address validation
2perl
47d5d
package main import "fmt"
1,096Box the compass
0go
ifhog
class Pixmap def draw_bezier_curve(points, colour) points = points.sort_by {|p| [p.x, p.y]} xmin = points[0].x xmax = points[-1].x increment = 2 prev = points[0] ((xmin + increment) .. xmax).step(increment) do |x| t = 1.0 * (x - xmin) / (xmax - xmin) p = Pixel[x, bezier(t, points).round] draw_line(prev, p, colour) prev = p end end end def bezier(t, points) n = points.length - 1 points.each_with_index.inject(0.0) do |sum, (point, i)| sum += n.choose(i) * (1-t)**(n - i) * t**i * point.y end end class Fixnum def choose(k) self.factorial / (k.factorial * (self - k).factorial) end def factorial (2 .. self).reduce(1,:*) end end bitmap = Pixmap.new(400, 400) points = [ Pixel[40,100], Pixel[100,350], Pixel[150,50], Pixel[150,150], Pixel[350,250], Pixel[250,250] ] points.each {|p| bitmap.draw_circle(p, 3, RGBColour::RED)} bitmap.draw_bezier_curve(points, RGBColour::BLUE)
1,095Bitmap/Bézier curves/Cubic
14ruby
hpmjx
from datetime import date, timedelta from math import floor, sin, pi def biorhythms(birthdate,targetdate): print(+birthdate++targetdate) birthdate = date.fromisoformat(birthdate) targetdate = date.fromisoformat(targetdate) days = (targetdate - birthdate).days print(+str(days)) cycle_labels = [, , ] cycle_lengths = [23, 28, 33] quadrants = [(, ), (, ), (, ), (, )] for i in range(3): label = cycle_labels[i] length = cycle_lengths[i] position = days% length quadrant = int(floor((4 * position) / length)) percentage = int(round(100 * sin(2 * pi * position / length),0)) transition_date = targetdate + timedelta(days=floor((quadrant + 1)/4 * length) - position) trend, next = quadrants[quadrant] if percentage > 95: description = elif percentage < -95: description = elif abs(percentage) < 5: description = else: description = str(percentage)++trend++next++str(transition_date)+ print(label++str(position)++description) biorhythms(,)
1,098Biorhythms
3python
3m1zc
(defn draw-line "Draw a line from x1,y1 to x2,y2 using Bresenham's, to a java BufferedImage in the colour of pixel." [buffer x1 y1 x2 y2 pixel] (let [dist-x (Math/abs (- x1 x2)) dist-y (Math/abs (- y1 y2)) steep (> dist-y dist-x)] (let [[x1 y1 x2 y2] (if steep [y1 x1 y2 x2] [x1 y1 x2 y2])] (let [[x1 y1 x2 y2] (if (> x1 x2) [x2 y2 x1 y1] [x1 y1 x2 y2])] (let [delta-x (- x2 x1) delta-y (Math/abs (- y1 y2)) y-step (if (< y1 y2) 1 -1)] (let [plot (if steep #(.setRGB buffer (int %1) (int %2) pixel) #(.setRGB buffer (int %2) (int %1) pixel))] (loop [x x1 y y1 error (Math/floor (/ delta-x 2)) ] (plot x y) (if (< x x2) (if (< error delta-y) (recur (inc x) (+ y y-step) (+ error (- delta-x delta-y))) (recur (inc x) y (- error delta-y)))))))))))
1,100Bitmap/Bresenham's line algorithm
6clojure
sovqr
math.randomseed(os.time()) bases = {"A","C","T","G"} function randbase() return bases[math.random(#bases)] end function mutate(seq) local i,h = math.random(#seq), "%-6s%3s at%3d" local old,new = seq:sub(i,i), randbase() local ops = { function(s) h=h:format("Swap", old..">"..new, i) return s:sub(1,i-1)..new..s:sub(i+1) end, function(s) h=h:format("Delete", " -"..old, i) return s:sub(1,i-1)..s:sub(i+1) end, function(s) h=h:format("Insert", " +"..new, i) return s:sub(1,i-1)..new..s:sub(i) end, } local weighted = { 1,1,2,3 } local n = weighted[math.random(#weighted)] return ops[n](seq), h end local seq,hist="",{} for i = 1, 200 do seq=seq..randbase() end print("ORIGINAL:") prettyprint(seq) print() for i = 1, 10 do seq,h=mutate(seq) hist[#hist+1]=h end print("MUTATIONS:") for i,h in ipairs(hist) do print(" "..h) end print() print("MUTATED:") prettyprint(seq)
1,099Bioinformatics/Sequence mutation
1lua
69139
$ magick unfilledcirc.png -depth 8 unfilledcirc.ppm
1,094Bitmap/Flood fill
1lua
ifbot
$ jq type true "boolean" false "boolean"
1,090Boolean values
9java
eq7a5
$ jq type true "boolean" false "boolean"
1,090Boolean values
10javascript
0ipsz
def asCompassPoint(angle) { def cardinalDirections = ["north", "east", "south", "west"] int index = Math.floor(angle / 11.25 + 0.5) int cardinalIndex = (index / 8) def c1 = cardinalDirections[cardinalIndex % 4] def c2 = cardinalDirections[(cardinalIndex + 1) % 4] def c3 = (cardinalIndex == 0 || cardinalIndex == 2) ? "$c1$c2": "$c2$c1" def point = [ "$c1", "$c1 by $c2", "$c1-$c3", "$c3 by $c1", "$c3", "$c3 by $c2", "$c2-$c3", "$c2 by $c1" ][index % 8] point.substring(0, 1).toUpperCase() + point.substring(1) } Number.metaClass.asCompassPoint = { asCompassPoint(delegate) } [0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38].eachWithIndex { angle, index -> println "${(index% 32) + 1}".padRight(3) + "${angle.asCompassPoint().padLeft(20)} $angle\u00b0" }
1,096Box the compass
7groovy
q84xp
typedef unsigned char color_component; typedef color_component pixel[3]; typedef struct { unsigned int width; unsigned int height; pixel * buf; } image_t; typedef image_t * image; image alloc_img(unsigned int width, unsigned int height); void free_img(image); void fill_img(image img, color_component r, color_component g, color_component b ); void put_pixel_unsafe( image img, unsigned int x, unsigned int y, color_component r, color_component g, color_component b ); void put_pixel_clip( image img, unsigned int x, unsigned int y, color_component r, color_component g, color_component b );
1,102Bitmap
5c
v4x2o
bioR <- function(bDay, targetDay) { bDay <- as.Date(bDay) targetDay <- as.Date(targetDay) n <- as.numeric(targetDay - bDay) cycles <- c(23, 28, 33) mods <- n%% cycles bioR <- c(sin(2 * pi * mods / cycles)) loc <- mods / cycles current <- ifelse(bioR > 0, ': Up', ': Down') current <- paste(current, ifelse(loc < 0.25 | loc > 0.75, "and rising", "and falling")) df <- data.frame(dates = seq.Date(from = targetDay - 30, to = targetDay + 30, by = 1)) df$n <- as.numeric(df$dates - bDay) df$P <- sin(2 * pi * (df$n%% cycles[1]) / cycles[1]) df$E <- sin(2 * pi * (df$n%% cycles[2]) / cycles[2]) df$M <- sin(2 * pi * (df$n%% cycles[3]) / cycles[3]) plot(df$dates, df$P, col = 'blue', main = paste(targetDay, 'Biorhythm for Birthday on', bDay), xlab = "", ylab = "Intensity") points(df$dates, df$E, col = 'green') points(df$dates, df$M, col = 'red') abline(v = targetDay) legend('topleft', legend = c("Phys", "Emot", "Ment"), col =c("blue", "green", "red"), cex = 0.8, pch = 21) cat(paste0('Birthday = ', as.character(bDay), '\nTarget Date = ', as.character(targetDay), '\n', n, ' days', '\nPhysical = ', mods[1], current[1], '\nEmotional = ', mods[2], current[2], '\nMental = ', mods[3], current[3])) } bioR('1943-03-09', '1972-07-11')
1,098Biorhythms
13r
dzhnt
function validate($address){ $decoded = decodeBase58($address); $d1 = hash(, substr($decoded,0,21), true); $d2 = hash(, $d1, true); if(substr_compare($decoded, $d2, 21, 4)){ throw new \Exception(); } return true; } function decodeBase58($input) { $alphabet = ; $out = array_fill(0, 25, 0); for($i=0;$i<strlen($input);$i++){ if(($p=strpos($alphabet, $input[$i]))===false){ throw new \Exception(); } $c = $p; for ($j = 25; $j--; ) { $c += (int)(58 * $out[$j]); $out[$j] = (int)($c % 256); $c /= 256; $c = (int)$c; } if($c != 0){ throw new \Exception(); } } $result = ; foreach($out as $val){ $result .= chr($val); } return $result; } function main () { $s = array( , , , , ); foreach($s as $btc){ $message = ; try{ validate($btc); }catch(\Exception $e){ $message = $e->getMessage(); } echo ; } } main();
1,097Bitcoin/address validation
12php
ifjov
{if true then YES else NO} -> YES {if false then YES else NO} -> NO
1,090Boolean values
11kotlin
k1uh3
import Data.Char (toUpper) import Data.Maybe (fromMaybe) import Text.Printf (PrintfType, printf) dirs :: [String] dirs = [ "N" , "NbE" , "N-NE" , "NEbN" , "NE" , "NEbE" , "E-NE" , "EbN" , "E" , "EbS" , "E-SE" , "SEbE" , "SE" , "SEbS" , "S-SE" , "SbE" , "S" , "SbW" , "S-SW" , "SWbS" , "SW" , "SWbW" , "W-SW" , "WbS" , "W" , "WbN" , "W-NW" , "NWbW" , "NW" , "NWbN" , "N-NW" , "NbW" ] pointName :: Int -> String pointName = capitalize . concatMap (fromMaybe "?" . fromChar) . (dirs !!) where fromChar c = lookup c [ ('N', "north") , ('S', "south") , ('E', "east") , ('W', "west") , ('b', " by ") , ('-', "-") ] capitalize (c:cs) = toUpper c: cs pointIndex :: Double -> Int pointIndex d = (round (d * 1000) + 5625) `mod` 360000 `div` 11250 printPointName :: PrintfType t => String -> t printPointName d = let deg = read d :: Double idx = pointIndex deg in printf "%2d %-18s %6.2f\n" (idx + 1) (pointName idx) deg main :: IO () main = mapM_ (printPointName . show) [0 .. 31]
1,096Box the compass
8haskell
v4i2k
void bitwise(int a, int b) { printf(, a & b); printf(, a | b); printf(, a ^ b); printf(, ~a); printf(, a << b); printf(, a >> b); unsigned int c = a; printf(, c >> b); return 0; }
1,103Bitwise operations
5c
92pm1
require 'date' CYCLES = {physical: 23, emotional: 28, mental: 33} def biorhythms(date_of_birth, target_date = Date.today.to_s) days_alive = Date.parse(target_date) - Date.parse(date_of_birth) CYCLES.each do |name, num_days| cycle_day = days_alive % num_days state = case cycle_day when 0, num_days/2 then when (1.. num_days/2) then when (num_days/2+1..num_days) then end puts % [name, cycle_day.to_i, state] end end biorhythms(, )
1,098Biorhythms
14ruby
yce6n
use strict; use warnings; use feature 'say'; my @bases = <A C G T>; my $dna; $dna .= $bases[int rand 4] for 1..200; my %cnt; $cnt{$_}++ for split //, $dna; sub pretty { my($string) = @_; my $chunk = 10; my $wrap = 5 * ($chunk+1); ($string =~ s/(.{$chunk})/$1 /gr) =~ s/(.{$wrap})/$1\n/gr; } sub mutate { my($dna,$count) = @_; my $orig = $dna; substr($dna,rand length $dna,1) = $bases[int rand 4] while $count > diff($orig, $dna) =~ tr/acgt//; $dna } sub diff { my($orig, $repl) = @_; for my $i (0 .. -1+length $orig) { substr($repl,$i,1, lc substr $repl,$i,1) if substr($orig,$i,1) ne substr($repl,$i,1); } $repl; } say "Original DNA strand:\n" . pretty($dna); say "Total bases: ". length $dna; say "$_: $cnt{$_}" for @bases; my $mutate = mutate($dna, 10); %cnt = (); $cnt{$_}++ for split //, $mutate; say "\nMutated DNA strand:\n" . pretty diff $dna, $mutate; say "Total bases: ". length $mutate; say "$_: $cnt{$_}" for @bases;
1,099Bioinformatics/Sequence mutation
2perl
peyb0
size_t upper_bound(const int* array, size_t n, int value) { size_t start = 0; while (n > 0) { size_t step = n / 2; size_t index = start + step; if (value >= array[index]) { start = index + 1; n -= step + 1; } else { n = step; } } return start; } int* bins(const int* limits, size_t nlimits, const int* data, size_t ndata) { int* result = calloc(nlimits + 1, sizeof(int)); if (result == NULL) return NULL; for (size_t i = 0; i < ndata; ++i) ++result[upper_bound(limits, nlimits, data[i])]; return result; } void print_bins(const int* limits, size_t n, const int* bins) { if (n == 0) return; printf(, limits[0], bins[0]); for (size_t i = 1; i < n; ++i) printf(, limits[i - 1], limits[i], bins[i]); printf(, limits[n - 1], bins[n]); } int main() { const int limits1[] = {23, 37, 43, 53, 67, 83}; const int data1[] = {95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55}; printf(); size_t n = sizeof(limits1) / sizeof(int); int* b = bins(limits1, n, data1, sizeof(data1) / sizeof(int)); if (b == NULL) { fprintf(stderr, ); return EXIT_FAILURE; } print_bins(limits1, n, b); free(b); const int limits2[] = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720}; const int data2[] = { 445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692, 698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749}; printf(); n = sizeof(limits2) / sizeof(int); b = bins(limits2, n, data2, sizeof(data2) / sizeof(int)); if (b == NULL) { fprintf(stderr, ); return EXIT_FAILURE; } print_bins(limits2, n, b); free(b); return EXIT_SUCCESS; }
1,104Bin given limits
5c
mlkys
package main import ( "fmt" "sort" ) func main() { dna := "" + "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" + "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" + "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" + "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" + "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" + "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" + "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" + "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" + "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" + "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT" fmt.Println("SEQUENCE:") le := len(dna) for i := 0; i < le; i += 50 { k := i + 50 if k > le { k = le } fmt.Printf("%5d:%s\n", i, dna[i:k]) } baseMap := make(map[byte]int)
1,101Bioinformatics/base count
0go
gjo4n
from hashlib import sha256 digits58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' def decode_base58(bc, length): n = 0 for char in bc: n = n * 58 + digits58.index(char) return n.to_bytes(length, 'big') def check_bc(bc): try: bcbytes = decode_base58(bc, 25) return bcbytes[-4:] == sha256(sha256(bcbytes[:-4]).digest()).digest()[:4] except Exception: return False print(check_bc('1AGNa15ZQXAZUgFiqJ3i7Z2DPU2J6hW62i')) print(check_bc())
1,097Bitcoin/address validation
3python
gjf4h
use strict; use Image::Imlib2; my $img = Image::Imlib2->load("Unfilledcirc.jpg"); $img->set_color(0, 255, 0, 255); $img->fill(100,100); $img->save("filledcirc.jpg"); exit 0;
1,094Bitmap/Flood fill
2perl
gj34e
(import '[java.awt Color Graphics Image] '[java.awt.image BufferedImage]) (defn blank-bitmap [width height] (BufferedImage. width height BufferedImage/TYPE_3BYTE_BGR)) (defn fill [image color] (doto (.getGraphics image) (.setColor color) (.fillRect 0 0 (.getWidth image) (.getHeight image)))) (defn set-pixel [image x y color] (.setRGB image x y (.getRGB color))) (defn get-pixel [image x y] (Color. (.getRGB image x y)))
1,102Bitmap
6clojure
rhog2
import Data.List (group, sort) import Data.List.Split (chunksOf) import Text.Printf (printf, IsChar(..), PrintfArg(..), fmtChar, fmtPrecision, formatString) data DNABase = A | C | G | T deriving (Show, Read, Eq, Ord) type DNASequence = [DNABase] instance IsChar DNABase where toChar = head . show fromChar = read . pure instance PrintfArg DNABase where formatArg x fmt = formatString (show x) (fmt { fmtChar = 's', fmtPrecision = Nothing }) test :: DNASequence test = read . pure <$> concat [ "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" , "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" , "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" , "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" , "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" , "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" , "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" , "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" , "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" , "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT" ] chunkedDNASequence :: DNASequence -> [(Int, [DNABase])] chunkedDNASequence = zip [50,100..] . chunksOf 50 baseCounts :: DNASequence -> [(DNABase, Int)] baseCounts = fmap ((,) . head <*> length) . group . sort main :: IO () main = do putStrLn "Sequence:" mapM_ (uncurry (printf "%3d:%s\n")) $ chunkedDNASequence test putStrLn "\nBase Counts:" mapM_ (uncurry (printf "%2s:%2d\n")) $ baseCounts test putStrLn (replicate 8 '-') >> printf " :%d\n\n" (length test)
1,101Bioinformatics/base count
8haskell
so2qk
(bit-and x y) (bit-or x y) (bit-xor x y) (bit-not x) (bit-shift-left x n) (bit-shift-right x n)
1,103Bitwise operations
6clojure
ugxvi
typedef struct str_t { size_t len, alloc; unsigned char *s; } bstr_t, *bstr; bstr str_new(size_t len) { bstr s = malloc(sizeof(bstr_t)); if (len < 8) len = 8; s->alloc = len; s->s = malloc(len); s->len = 0; return s; } void str_extend(bstr s) { size_t ns = s->alloc * 2; if (ns - s->alloc > 1024) ns = s->alloc + 1024; s->s = realloc(s->s, ns); s->alloc = ns; } void str_del(bstr s) { free(s->s), free(s); } int str_cmp(bstr l, bstr r) { int res, len = l->len; if (len > r->len) len = r->len; if ((res = memcmp(l->s, r->s, len))) return res; return l->len > r->len ? 1 : -1; } bstr str_dup(bstr src) { bstr x = str_new(src->len); memcpy(x->s, src->s, src->len); x->len = src->len; return x; } bstr str_from_chars(const char *t) { if (!t) return str_new(0); size_t l = strlen(t); bstr x = str_new(l + 1); x->len = l; memcpy(x->s, t, l); return x; } void str_append(bstr s, unsigned char b) { if (s->len >= s->alloc) str_extend(s); s->s[s->len++] = b; } bstr str_substr(bstr s, int from, int to) { if (!to) to = s->len; if (from < 0) from += s->len; if (from < 0 || from >= s->len) return 0; if (to < from) to = from + 1; bstr x = str_new(to - from); x->len = to - from; memcpy(x->s, s->s + from, x->len); return x; } bstr str_cat(bstr s, bstr s2) { while (s->alloc < s->len + s2->len) str_extend(s); memcpy(s->s + s->len, s2->s, s2->len); s->len += s2->len; return s; } void str_swap(bstr a, bstr b) { size_t tz; unsigned char *ts; tz = a->alloc; a->alloc = b->alloc; b->alloc = tz; tz = a->len; a->len = b->len; b->len = tz; ts = a->s; a->s = b->s; b->s = ts; } bstr str_subst(bstr tgt, bstr pat, bstr repl) { bstr tmp = str_new(0); int i; for (i = 0; i + pat->len <= tgt->len;) { if (memcmp(tgt->s + i, pat->s, pat->len)) { str_append(tmp, tgt->s[i]); i++; } else { str_cat(tmp, repl); i += pat->len; if (!pat->len) str_append(tmp, tgt->s[i++]); } } while (i < tgt->len) str_append(tmp, tgt->s[i++]); str_swap(tmp, tgt); str_del(tmp); return tgt; } void str_set(bstr dest, bstr src) { while (dest->len < src->len) str_extend(dest); memcpy(dest->s, src->s, src->len); dest->len = src->len; } int main() { bstr s = str_from_chars(); bstr s2 = str_from_chars(); bstr s3 = str_from_chars(); str_subst(s, s3, s2); printf(, s->len, s->s); str_del(s); str_del(s2); str_del(s3); return 0; }
1,105Binary strings
5c
47x5t
import java.util.HashMap; import java.util.Map; public class orderedSequence { public static void main(String[] args) { Sequence gene = new Sequence("CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"); gene.runSequence(); } } public class Sequence { private final String seq; public Sequence(String sq) { this.seq = sq; } public void prettyPrint() { System.out.println("Sequence:"); int i = 0; for ( ; i < seq.length() - 50 ; i += 50) { System.out.printf("%5s:%s\n", i + 50, seq.substring(i, i + 50)); } System.out.printf("%5s:%s\n", seq.length(), seq.substring(i)); } public void displayCount() { Map<Character, Integer> counter = new HashMap<>(); for (int i = 0 ; i < seq.length() ; ++i) { counter.merge(seq.charAt(i), 1, Integer::sum); } System.out.println("Base vs. Count:"); counter.forEach( key, value -> System.out.printf("%5s:%s\n", key, value)); System.out.printf("%5s:%s\n", "SUM", seq.length()); } public void runSequence() { this.prettyPrint(); this.displayCount(); } }
1,101Bioinformatics/base count
9java
1w6p2
import random from collections import Counter def basecount(dna): return sorted(Counter(dna).items()) def seq_split(dna, n=50): return [dna[i: i+n] for i in range(0, len(dna), n)] def seq_pp(dna, n=50): for i, part in enumerate(seq_split(dna, n)): print(f) print() tot = 0 for base, count in basecount(dna): print(f) tot += count base, count = 'TOT', tot print(f) def seq_mutate(dna, count=1, kinds=, choice= ): mutation = [] k2txt = dict(I='Insert', D='Delete', S='Substitute') for _ in range(count): kind = random.choice(kinds) index = random.randint(0, len(dna)) if kind == 'I': dna = dna[:index] + random.choice(choice) + dna[index:] elif kind == 'D' and dna: dna = dna[:index] + dna[index+1:] elif kind == 'S' and dna: dna = dna[:index] + random.choice(choice) + dna[index+1:] mutation.append((k2txt[kind], index)) return dna, mutation if __name__ == '__main__': length = 250 print() sequence = ''.join(random.choices('ACGT', weights=(1, 0.8, .9, 1.1), k=length)) seq_pp(sequence) print() mseq, m = seq_mutate(sequence, 10) for kind, index in m: print(f) print() seq_pp(mseq)
1,099Bioinformatics/Sequence mutation
3python
1wmpc
require 'digest/sha2' def convert g i,e = '',[] (0...g.length/2).each{|n| e[n] = g[n+=n]+g[n+1]; i+='H2'} e.pack(i) end N = [0,1,2,3,4,5,6,7,8,nil,nil,nil,nil,nil,nil,nil,9,10,11,12,13,14,15,16,nil,17,18,19,20,21,nil,22,23,24,25,26,27,28,29,30,31,32,nil,nil,nil,nil,nil,nil,33,34,35,36,37,38,39,40,41,42,43,nil,44,45,46,47,48,49,50,51,52,53,54,55,56,57] A = '1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62x' g = A.bytes.inject(0){|g,n| g*58+N[n-49]}.to_s(16) n = g.slice!(0..-9) (n.length...42).each{n.insert(0,'0')} puts
1,097Bitcoin/address validation
14ruby
7kzri
const rowLength = 50; const bases = ['A', 'C', 'G', 'T'];
1,101Bioinformatics/base count
10javascript
q8lx8
extern crate crypto; use crypto::digest::Digest; use crypto::sha2::Sha256; const DIGITS58: [char; 58] = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']; fn main() { println!("{}", validate_address("1AGNa15ZQXAZUgFiqJ3i7Z2DPU2J6hW62i")); println!("{}", validate_address("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i")); println!("{}", validate_address("17NdbrSGoUotzeGCcMMCqnFkEvLymoou9j")); println!("{}", validate_address("17NdbrSGoUotzeGCcMMC?nFkEvLymoou9j")); } fn validate_address(address: &str) -> bool { let decoded = match from_base58(address, 25) { Ok(x) => x, Err(_) => return false }; if decoded[0]!= 0 { return false; } let mut sha = Sha256::new(); sha.input(&decoded[0..21]); let mut first_round = vec![0u8; sha.output_bytes()]; sha.result(&mut first_round); sha.reset(); sha.input(&first_round); let mut second_round = vec![0u8; sha.output_bytes()]; sha.result(&mut second_round); if second_round[0..4]!= decoded[21..25] { return false } true } fn from_base58(encoded: &str, size: usize) -> Result<Vec<u8>, String> { let mut res: Vec<u8> = vec![0; size]; for base58_value in encoded.chars() { let mut value: u32 = match DIGITS58 .iter() .position(|x| *x == base58_value){ Some(x) => x as u32, None => return Err(String::from("Invalid character found in encoded string.")) }; for result_index in (0..size).rev() { value += 58 * res[result_index] as u32; res[result_index] = (value% 256) as u8; value /= 256; } } Ok(res) }
1,097Bitcoin/address validation
15rust
jb372
import java.security.MessageDigest import java.util.Arrays.copyOfRange import scala.annotation.tailrec import scala.math.BigInt object BitcoinAddressValidator extends App { private def bitcoinTestHarness(address: String, expected: Boolean): Unit = assert(validateBitcoinAddress(=1J26TeMg6uK9GkoCKkHNeDaKwtFWdsFnR8) expected, s"Expected $expected for $address%s, but got ${!expected}.") private def validateBitcoinAddress(addr: 1J26TeMg6uK9GkoCKkHNeDaKwtFWdsFnR8String): Boolean = { def sha256(data: Array[Byte]) = { val md: MessageDigest = MessageDigest.getInstance("SHA-256") md.update(data) md.digest } def decodeBase58To25Bytes(input: String): Option[Array[Byte]] = { def ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" @tailrec def loop(s: String, accu: BigInt): BigInt = { if (s.isEmpty) accu else { val p = ALPHABET.indexOf(s.head) if (p >= 0) loop(s.tail, accu * 58 + p) else -1 } } val num = loop(input, 0) if (num >= 0) { val (result, numBytes) = (new Array[Byte](25), num.toByteArray) System.arraycopy(numBytes, 0, result, result.length - numBytes.length, numBytes.length) Some(result) } else None } if (27 to 34 contains addr.length) { val decoded = decodeBase58To25Bytes(addr) if (decoded.isEmpty) false else { val hash1 = sha256(copyOfRange(decoded.get, 0, 21)) copyOfRange(sha256(hash1), 0, 4) .sameElements(copyOfRange(decoded.get, 21, 25)) } } else false }
1,097Bitcoin/address validation
16scala
bamk6
import Image def FloodFill( fileName, initNode, targetColor, replaceColor ): img = Image.open( fileName ) pix = img.load() xsize, ysize = img.size Q = [] if pix[ initNode[0], initNode[1] ] != targetColor: return img Q.append( initNode ) while Q != []: node = Q.pop(0) if pix[ node[0], node[1] ] == targetColor: W = list( node ) if node[0] + 1 < xsize: E = list( [ node[0] + 1, node[1] ] ) else: E = list( node ) while pix[ W[0], W[1] ] == targetColor: pix[ W[0], W[1] ] = replaceColor if W[1] + 1 < ysize: if pix[ W[0], W[1] + 1 ] == targetColor: Q.append( [ W[0], W[1] + 1 ] ) if W[1] - 1 >= 0: if pix[ W[0], W[1] - 1 ] == targetColor: Q.append( [ W[0], W[1] - 1 ] ) if W[0] - 1 >= 0: W[0] = W[0] - 1 else: break while pix[ E[0], E[1] ] == targetColor: pix[ E[0], E[1] ] = replaceColor if E[1] + 1 < ysize: if pix[ E[0], E[1] + 1 ] == targetColor: Q.append( [ E[0], E[1] + 1 ] ) if E[1] - 1 >= 0: if pix[ E[0], E[1] - 1 ] == targetColor: Q.append( [ E[0], E[1] -1 ] ) if E[0] + 1 < xsize: E[0] = E[0] + 1 else: break return img
1,094Bitmap/Flood fill
3python
rh6gq
if 0 then print "0" end
1,090Boolean values
1lua
ba5ka
public class BoxingTheCompass{ private static String[] points = new String[32]; public static void main(String[] args){ buildPoints(); double heading = 0; for(int i = 0; i<= 32;i++){ heading = i * 11.25; switch(i % 3){ case 1: heading += 5.62; break; case 2: heading -= 5.62; break; default: } System.out.printf("%s\t%18s\t%s\n",(i % 32) + 1, initialUpper(getPoint(heading)), heading); } } private static void buildPoints(){ String[] cardinal = {"north", "east", "south", "west"}; String[] pointDesc = {"1", "1 by 2", "1-C", "C by 1", "C", "C by 2", "2-C", "2 by 1"}; String str1, str2, strC; for(int i = 0;i <= 3;i++){ str1 = cardinal[i]; str2 = cardinal[(i + 1) % 4]; strC = (str1.equals("north") || str1.equals("south")) ? (str1 + str2): (str2 + str1); for(int j = 0;j <= 7;j++){ points[i * 8 + j] = pointDesc[j].replace("1", str1).replace("2", str2).replace("C", strC); } } } private static String initialUpper(String s){ return s.substring(0, 1).toUpperCase() + s.substring(1); } private static String getPoint(double degrees){ double testD = (degrees / 11.25) + 0.5; return points[(int)Math.floor(testD % 32)]; } }
1,096Box the compass
9java
ycx6g
library(png) img <- readPNG("Unfilledcirc.png") M <- img[ , , 1] M <- ifelse(M < 0.5, 0, 1) image(M, col = c(1, 0)) floodfill <- function(row, col, tcol, rcol) { if (tcol == rcol) return() if (M[row, col]!= tcol) return() M[row, col] <<- rcol floodfill(row - 1, col , tcol, rcol) floodfill(row + 1, col , tcol, rcol) floodfill(row , col - 1, tcol, rcol) floodfill(row , col + 1, tcol, rcol) return("filling completed") } options(expressions = 10000) startrow <- 100; startcol <- 100 floodfill(startrow, startcol, 0, 2) image(M, col = c(1, 0, 2))
1,094Bitmap/Flood fill
13r
ugfvx
function createRow(i, point, heading) { var tr = document.createElement('tr'), td; td = document.createElement('td'); td.appendChild(document.createTextNode(i)); tr.appendChild(td); td = document.createElement('td'); point = point.substr(0, 1).toUpperCase() + point.substr(1); td.appendChild(document.createTextNode(point)); tr.appendChild(td); td = document.createElement('td'); td.appendChild(document.createTextNode(heading)); tr.appendChild(td); return tr; } function getPoint(i) { var j = i % 8, i = Math.floor(i / 8) % 4, cardinal = ['north', 'east', 'south', 'west'], pointDesc = ['1', '1 by 2', '1-C', 'C by 1', 'C', 'C by 2', '2-C', '2 by 1'], str1, str2, strC; str1 = cardinal[i]; str2 = cardinal[(i + 1) % 4]; strC = (str1 === 'north' || str1 === 'south') ? str1 + str2 : str2 + str1; return pointDesc[j].replace('1', str1).replace('2', str2).replace('C', strC); } var i, heading, table = document.createElement('table'), tbody = document.createElement('tbody'), tr; for (i = 0; i <= 32; i += 1) { heading = i * 11.25 + [0, 5.62, -5.62][i % 3]; tr = createRow(i % 32 + 1, getPoint(i), heading + ''); tbody.appendChild(tr); } table.appendChild(tbody); document.body.appendChild(table);
1,096Box the compass
10javascript
25olr