code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
package main import ( "fmt" "log" "math" "os" "path/filepath" ) func commatize(n int64) string { s := fmt.Sprintf("%d", n) if n < 0 { s = s[1:] } le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } if n >= 0 { return s } return "-" + s } func fileSizeDistribution(root string) { var sizes [12]int files := 0 directories := 0 totalSize := int64(0) walkFunc := func(path string, info os.FileInfo, err error) error { if err != nil { return err } files++ if info.IsDir() { directories++ } size := info.Size() if size == 0 { sizes[0]++ return nil } totalSize += size logSize := math.Log10(float64(size)) index := int(math.Floor(logSize)) sizes[index+1]++ return nil } err := filepath.Walk(root, walkFunc) if err != nil { log.Fatal(err) } fmt.Printf("File size distribution for '%s':-\n\n", root) for i := 0; i < len(sizes); i++ { if i == 0 { fmt.Print(" ") } else { fmt.Print("+ ") } fmt.Printf("Files less than 10 ^%-2d bytes:%5d\n", i, sizes[i]) } fmt.Println(" -----") fmt.Printf("= Total number of files :%5d\n", files) fmt.Printf(" including directories :%5d\n", directories) c := commatize(totalSize) fmt.Println("\n Total size of files :", c, "bytes") } func main() { fileSizeDistribution("./") }
842File size distribution
0go
s3aqa
int common_len(const char *const *names, int n, char sep) { int i, pos; for (pos = 0; ; pos++) { for (i = 0; i < n; i++) { if (names[i][pos] != '\0' && names[i][pos] == names[0][pos]) continue; while (pos > 0 && names[0][--pos] != sep); return pos; } } return 0; } int main() { const char *names[] = { , , , }; int len = common_len(names, sizeof(names) / sizeof(const char*), '/'); if (!len) printf(); else printf(, len, names[0]); return 0; }
843Find common directory path
5c
upmv4
(() => { 'use strict';
840Find palindromic numbers in both binary and ternary bases
10javascript
pohb7
import Control.Concurrent (forkIO, setNumCapabilities) import Control.Concurrent.Chan (Chan, newChan, readChan, writeChan, writeList2Chan) import Control.Exception (IOException, catch) import Control.Monad (filterM, forever, join, replicateM, replicateM_, (>=>)) import Control.Parallel.Strategies (parTraversable, rseq, using, withStrategy) import Data.Char (isDigit) import Data.List (find, sort) import qualified Data.Map.Strict as Map import GHC.Conc (getNumProcessors) import System.Directory (doesDirectoryExist, doesFileExist, listDirectory, pathIsSymbolicLink) import System.Environment (getArgs) import System.FilePath.Posix ((</>)) import System.IO (FilePath, IOMode (ReadMode), hFileSize, hPutStrLn, stderr, withFile) import Text.Printf (hPrintf, printf) data Item = File FilePath Integer | Folder FilePath deriving (Show) type FGKey = (Integer, Integer) type FrequencyGroup = (FGKey, Integer) type FrequencyGroups = Map.Map FGKey Integer newFrequencyGroups :: FrequencyGroups newFrequencyGroups = Map.empty fileSizes :: [Item] -> [Integer] fileSizes = foldr f [] where f (File _ n) acc = n:acc f _ acc = acc folders :: [Item] -> [FilePath] folders = foldr f [] where f (Folder p) acc = p:acc f _ acc = acc totalBytes :: [Item] -> Integer totalBytes = sum . fileSizes counts :: [Item] -> (Integer, Integer) counts = foldr (\x (a, b) -> case x of File _ _ -> (succ a, b) Folder _ -> (a, succ b)) (0, 0) frequencyGroups :: Int -> [Integer] -> FrequencyGroups frequencyGroups _ [] = newFrequencyGroups frequencyGroups totalGroups xs | length xs == 1 = Map.singleton (head xs, head xs) 1 | otherwise = foldr placeGroups newFrequencyGroups xs `using` parTraversable rseq where range = maximum xs - minimum xs groupSize = succ $ ceiling $ realToFrac range / realToFrac totalGroups groups = takeWhile (<=groupSize + maximum xs) $ iterate (+groupSize) 0 groupMinMax = zip groups (pred <$> tail groups) findGroup n = find (\(low, high) -> n >= low && n <= high) incrementCount (Just n) = Just (succ n) incrementCount Nothing = Just 1 placeGroups n fgMap = case findGroup n groupMinMax of Just k -> Map.alter incrementCount k fgMap Nothing -> fgMap expandGroups :: Int -> [Integer] -> Integer -> FrequencyGroups expandGroups gsize fileSizes groupThreshold | groupThreshold > 0 = loop 15 $ frequencyGroups gsize sortedFileSizes | otherwise = frequencyGroups gsize sortedFileSizes where sortedFileSizes = sort fileSizes loop 0 gs = gs loop n gs | all (<= groupThreshold) $ Map.elems gs = gs | otherwise = loop (pred n) (expand gs) expand :: FrequencyGroups -> FrequencyGroups expand = foldr f . withStrategy (parTraversable rseq) <*> Map.mapWithKey groupsFromGroup . Map.filter (> groupThreshold) where f :: Maybe (FGKey, FrequencyGroups) -> FrequencyGroups -> FrequencyGroups f (Just (k, fg)) acc = Map.union (Map.delete k acc) fg f Nothing acc = acc groupsFromGroup :: FGKey -> Integer -> Maybe (FGKey, FrequencyGroups) groupsFromGroup (min, max) count | length range > 1 = Just ((min, max), frequencyGroups gsize range) | otherwise = Nothing where range = filter (\n -> n >= min && n <= max) sortedFileSizes displaySize :: Integer -> String displaySize n | n <= 2^10 = printf "%8dB " n | n >= 2^10 && n <= 2^20 = display (2^10) "KB" | n >= 2^20 && n <= 2^30 = display (2^20) "MB" | n >= 2^30 && n <= 2^40 = display (2^30) "GB" | n >= 2^40 && n <= 2^50 = display (2^40) "TB" | otherwise = "Too large!" where display :: Double -> String -> String display b = printf "%7.2f%s " (realToFrac n / b) displayFrequency :: Integer -> FrequencyGroup -> IO () displayFrequency filesCount ((min, max), count) = do printf "%s <->%s" (displaySize min) (displaySize max) printf "=%-10d%6.3f%%:%-5s\n" count percentage bars where percentage :: Double percentage = (realToFrac count / realToFrac filesCount) * 100 size = round percentage bars | size == 0 = "" | otherwise = replicate size '' folderWorker :: Chan FilePath -> Chan [Item] -> IO () folderWorker folderChan resultItemsChan = forever (readChan folderChan >>= collectItems >>= writeChan resultItemsChan) collectItems :: FilePath -> IO [Item] collectItems folderPath = catch tryCollect $ \e -> do hPrintf stderr "Skipping:%s\n" $ show (e :: IOException) pure [] where tryCollect = (fmap (folderPath </>) <$> listDirectory folderPath) >>= mapM (\p -> doesDirectoryExist p >>= \case True -> pure $ Folder p False -> File p <$> withFile p ReadMode hFileSize) parallelItemCollector :: FilePath -> IO [Item] parallelItemCollector folder = do wCount <- getNumProcessors setNumCapabilities wCount printf "Using%d worker threads\n" wCount folderChan <- newChan resultItemsChan <- newChan replicateM_ wCount (forkIO $ folderWorker folderChan resultItemsChan) loop folderChan resultItemsChan [Folder folder] where loop :: Chan FilePath -> Chan [Item] -> [Item] -> IO [Item] loop folderChan resultItemsChan xs = do regularFolders <- filterM (pathIsSymbolicLink >=> (pure . not)) $ folders xs if null regularFolders then pure [] else do writeList2Chan folderChan regularFolders childItems <- replicateM (length regularFolders) (readChan resultItemsChan) result <- mapM (loop folderChan resultItemsChan) childItems pure (join childItems <> join result) parseArgs :: [String] -> Either String (FilePath, Int) parseArgs (x:y:xs) | all isDigit y = Right (x, read y) | otherwise = Left "Invalid frequency group size" parseArgs (x:xs) = Right (x, 4) parseArgs _ = Right (".", 4) main :: IO () main = parseArgs <$> getArgs >>= \case Left errorMessage -> hPutStrLn stderr errorMessage Right (path, groupSize) -> do items <- parallelItemCollector path let (fileCount, folderCount) = counts items printf "Total files:%d\nTotal folders:%d\n" fileCount folderCount printf "Total size:%s\n" $ displaySize $ totalBytes items printf "\nDistribution:\n\n%9s <->%9s%7s\n" "From" "To" "Count" putStrLn $ replicate 46 '-' let results = expandGroups groupSize (fileSizes items) (groupThreshold fileCount) mapM_ (displayFrequency fileCount) $ Map.assocs results where groupThreshold = round . (*0.25) . realToFrac
842File size distribution
8haskell
97zmo
import kotlin.math.max import kotlin.math.min private const val EPS = 0.001 private const val EPS_SQUARE = EPS * EPS private fun test(t: Triangle, p: Point) { println(t) println("Point $p is within triangle? ${t.within(p)}") } fun main() { var p1 = Point(1.5, 2.4) var p2 = Point(5.1, -3.1) var p3 = Point(-3.8, 1.2) var tri = Triangle(p1, p2, p3) test(tri, Point(0.0, 0.0)) test(tri, Point(0.0, 1.0)) test(tri, Point(3.0, 1.0)) println() p1 = Point(1.0 / 10, 1.0 / 9) p2 = Point(100.0 / 8, 100.0 / 3) p3 = Point(100.0 / 4, 100.0 / 9) tri = Triangle(p1, p2, p3) val pt = Point(p1.x + 3.0 / 7 * (p2.x - p1.x), p1.y + 3.0 / 7 * (p2.y - p1.y)) test(tri, pt) println() p3 = Point(-100.0 / 8, 100.0 / 6) tri = Triangle(p1, p2, p3) test(tri, pt) } class Point(val x: Double, val y: Double) { override fun toString(): String { return "($x, $y)" } } class Triangle(private val p1: Point, private val p2: Point, private val p3: Point) { private fun pointInTriangleBoundingBox(p: Point): Boolean { val xMin = min(p1.x, min(p2.x, p3.x)) - EPS val xMax = max(p1.x, max(p2.x, p3.x)) + EPS val yMin = min(p1.y, min(p2.y, p3.y)) - EPS val yMax = max(p1.y, max(p2.y, p3.y)) + EPS return !(p.x < xMin || xMax < p.x || p.y < yMin || yMax < p.y) } private fun nativePointInTriangle(p: Point): Boolean { val checkSide1 = side(p1, p2, p) >= 0 val checkSide2 = side(p2, p3, p) >= 0 val checkSide3 = side(p3, p1, p) >= 0 return checkSide1 && checkSide2 && checkSide3 } private fun distanceSquarePointToSegment(p1: Point, p2: Point, p: Point): Double { val p1P2SquareLength = (p2.x - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y) val dotProduct = ((p.x - p1.x) * (p2.x - p1.x) + (p.y - p1.y) * (p2.y - p1.y)) / p1P2SquareLength if (dotProduct < 0) { return (p.x - p1.x) * (p.x - p1.x) + (p.y - p1.y) * (p.y - p1.y) } if (dotProduct <= 1) { val pP1SquareLength = (p1.x - p.x) * (p1.x - p.x) + (p1.y - p.y) * (p1.y - p.y) return pP1SquareLength - dotProduct * dotProduct * p1P2SquareLength } return (p.x - p2.x) * (p.x - p2.x) + (p.y - p2.y) * (p.y - p2.y) } private fun accuratePointInTriangle(p: Point): Boolean { if (!pointInTriangleBoundingBox(p)) { return false } if (nativePointInTriangle(p)) { return true } if (distanceSquarePointToSegment(p1, p2, p) <= EPS_SQUARE) { return true } return if (distanceSquarePointToSegment(p2, p3, p) <= EPS_SQUARE) { true } else distanceSquarePointToSegment(p3, p1, p) <= EPS_SQUARE } fun within(p: Point): Boolean { return accuratePointInTriangle(p) } override fun toString(): String { return "Triangle[$p1, $p2, $p3]" } companion object { private fun side(p1: Point, p2: Point, p: Point): Double { return (p2.y - p1.y) * (p.x - p1.x) + (-p2.x + p1.x) * (p.y - p1.y) } } }
839Find if a point is within a triangle
11kotlin
2kcli
null
840Find palindromic numbers in both binary and ternary bases
11kotlin
uplvc
const char *filename = ; int main() { struct stat foo; time_t mtime; struct utimbuf new_times; if (stat(filename, &foo) < 0) { perror(filename); return 1; } mtime = foo.st_mtime; new_times.actime = foo.st_atime; new_times.modtime = time(NULL); if (utime(filename, &new_times) < 0) { perror(filename); return 1; } return 0; }
844File modification time
5c
gec45
null
842File size distribution
11kotlin
omx8z
EPS = 0.001 EPS_SQUARE = EPS * EPS function side(x1, y1, x2, y2, x, y) return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1) end function naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) local checkSide1 = side(x1, y1, x2, y2, x, y) >= 0 local checkSide2 = side(x2, y2, x3, y3, x, y) >= 0 local checkSide3 = side(x3, y3, x1, y1, x, y) >= 0 return checkSide1 and checkSide2 and checkSide3 end function pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) local xMin = math.min(x1, x2, x3) - EPS local xMax = math.max(x1, x2, x3) + EPS local yMin = math.min(y1, y2, y3) - EPS local yMax = math.max(y1, y2, y3) + EPS return not (x < xMin or xMax < x or y < yMin or yMax < y) end function distanceSquarePointToSegment(x1, y1, x2, y2, x, y) local p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1) local dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength if dotProduct < 0 then return (x - x1) * (x - x1) + (y - y1) * (y - y1) end if dotProduct <= 1 then local p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y) return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength end return (x - x2) * (x - x2) + (y - y2) * (y - y2) end function accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) if not pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) then return false end if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) then return true end if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE then return true end if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE then return true end if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE then return true end return false end function printPoint(x, y) io.write('('..x..", "..y..')') end function printTriangle(x1, y1, x2, y2, x3, y3) io.write("Triangle is [") printPoint(x1, y1) io.write(", ") printPoint(x2, y2) io.write(", ") printPoint(x3, y3) print("]") end function test(x1, y1, x2, y2, x3, y3, x, y) printTriangle(x1, y1, x2, y2, x3, y3) io.write("Point ") printPoint(x, y) print(" is within triangle? " .. tostring(accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y))) end test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0) test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1) test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1) print() test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348) print() test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348) print()
839Find if a point is within a triangle
1lua
vbl2x
use File::Find; use List::Util qw(max); my %fsize; $dir = shift || '.'; find(\&fsize, $dir); $max = max($max,$fsize{$_}) for keys %fsize; $total += $size while (undef,$size) = each %fsize; print "File size distribution in bytes for directory: $dir\n"; for (0 .. max(keys %fsize)) { printf " histogram( $max, $fsize{$_} // 0, 80); } print "$total total files.\n"; sub histogram { my($max, $value, $width) = @_; my @blocks = qw<| >; my $scaled = int $value * $width / $max; my $end = $scaled % 8; my $bar = int $scaled / 8; my $B = $blocks[8] x ($bar * 8) . ($end ? $blocks[$end] : ''); } sub fsize { $fsize{ log10( (lstat($_))[7] ) }++ } sub log10 { my($s) = @_; $s ? int log($s)/log(10) : 0 }
842File size distribution
2perl
ge24e
(use '[clojure.string:only [join,split]]) (defn common-prefix [sep paths] (let [parts-per-path (map #(split % (re-pattern sep)) paths) parts-per-position (apply map vector parts-per-path)] (join sep (for [parts parts-per-position:while (apply = parts)] (first parts))))) (println (common-prefix "/" ["/home/user1/tmp/coverage/test" "/home/user1/tmp/covert/operator" "/home/user1/tmp/coven/members"]))
843Find common directory path
6clojure
7xvr0
(import '(java.io File) '(java.util Date)) (Date. (.lastModified (File. "output.txt"))) (Date. (.lastModified (File. "docs"))) (.setLastModified (File. "output.txt") (.lastModified (File. "docs")))
844File modification time
6clojure
k05hs
use strict; use warnings; use List::AllUtils qw(min max natatime); use constant EPSILON => 0.001; use constant EPSILON_SQUARE => EPSILON*EPSILON; sub side { my ($x1, $y1, $x2, $y2, $x, $y) = @_; return ($y2 - $y1)*($x - $x1) + (-$x2 + $x1)*($y - $y1); } sub naivePointInTriangle { my ($x1, $y1, $x2, $y2, $x3, $y3, $x, $y) = @_; my $checkSide1 = side($x1, $y1, $x2, $y2, $x, $y) >= 0 ; my $checkSide2 = side($x2, $y2, $x3, $y3, $x, $y) >= 0 ; my $checkSide3 = side($x3, $y3, $x1, $y1, $x, $y) >= 0 ; return $checkSide1 && $checkSide2 && $checkSide3 || 0 ; } sub pointInTriangleBoundingBox { my ($x1, $y1, $x2, $y2, $x3, $y3, $x, $y) = @_; my $xMin = min($x1, min($x2, $x3)) - EPSILON; my $xMax = max($x1, max($x2, $x3)) + EPSILON; my $yMin = min($y1, min($y2, $y3)) - EPSILON; my $yMax = max($y1, max($y2, $y3)) + EPSILON; ( $x < $xMin || $xMax < $x || $y < $yMin || $yMax < $y ) ? 0 : 1 } sub distanceSquarePointToSegment { my ($x1, $y1, $x2, $y2, $x, $y) = @_; my $p1_p2_squareLength = ($x2 - $x1)**2 + ($y2 - $y1)**2; my $dotProduct = ($x-$x1)*($x2-$x1)+($y-$y1)*($y2-$y1) ; if ( $dotProduct < 0 ) { return ($x - $x1)**2 + ($y - $y1)**2; } elsif ( $dotProduct <= $p1_p2_squareLength ) { my $p_p1_squareLength = ($x1 - $x)**2 + ($y1 - $y)**2; return $p_p1_squareLength - $dotProduct**2 / $p1_p2_squareLength; } else { return ($x - $x2)**2 + ($y - $y2)**2; } } sub accuratePointInTriangle { my ($x1, $y1, $x2, $y2, $x3, $y3, $x, $y) = @_; return 0 unless pointInTriangleBoundingBox($x1,$y1,$x2,$y2,$x3,$y3,$x,$y); return 1 if ( naivePointInTriangle($x1, $y1, $x2, $y2, $x3, $y3, $x, $y) or distanceSquarePointToSegment($x1, $y1, $x2, $y2, $x, $y) <= EPSILON_SQUARE or distanceSquarePointToSegment($x2, $y2, $x3, $y3, $x, $y) <= EPSILON_SQUARE or distanceSquarePointToSegment($x3, $y3, $x1, $y1, $x, $y) <= EPSILON_SQUARE); return 0 } my @DATA = (1.5, 2.4, 5.1, -3.1, -3.8, 0.5); for my $point ( [0,0] , [0,1] ,[3,1] ) { print "Point (", join(',',@$point), ") is within triangle "; my $iter = natatime 2, @DATA; while ( my @vertex = $iter->()) { print '(',join(',',@vertex),') ' } print ': ',naivePointInTriangle (@DATA, @$point) ? 'True' : 'False', "\n" ; }
839Find if a point is within a triangle
2perl
s3xq3
use ntheory qw/fromdigits todigitstring/; print "0 0 0\n"; for (0..2e5) { my $pal = todigitstring($_, 3); my $b3 = $pal . "1" . reverse($pal); my $b2 = todigitstring(fromdigits($b3, 3), 2); print fromdigits($b2,2)," $b3 $b2\n" if $b2 eq reverse($b2); }
840Find palindromic numbers in both binary and ternary bases
2perl
8yq0w
import sys, os from collections import Counter def dodir(path): global h for name in os.listdir(path): p = os.path.join(path, name) if os.path.islink(p): pass elif os.path.isfile(p): h[os.stat(p).st_size] += 1 elif os.path.isdir(p): dodir(p) else: pass def main(arg): global h h = Counter() for dir in arg: dodir(dir) s = n = 0 for k, v in sorted(h.items()): print(% (k, v)) n += v s += k * v print(% (s, n)) main(sys.argv[1:])
842File size distribution
3python
rwvgq
package main import ( "flag" "fmt" "runtime/debug" ) func main() { stack := flag.Int("stack", 0, "maximum per goroutine stack size or 0 for the default") flag.Parse() if *stack > 0 { debug.SetMaxStack(*stack) } r(1) } func r(l int) { if l%1000 == 0 { fmt.Println(l) } r(l + 1) }
841Find limit of recursion
0go
1ihp5
long getFileSize(const char *filename) { long result; FILE *fh = fopen(filename, ); fseek(fh, 0, SEEK_END); result = ftell(fh); fclose(fh); return result; } int main(void) { printf(, getFileSize()); printf(, getFileSize()); return 0; }
845File size
5c
2kzlo
int main(void) { puts( ); char i; for (i = 'c'; i <= 'z'; i++) printf(, i, i-1, i-2); puts(); return 0; }
846Fibonacci word/fractal
5c
ncei6
from sympy.geometry import Point, Triangle def sign(pt1, pt2, pt3): return (pt1.x - pt3.x) * (pt2.y - pt3.y) - (pt2.x - pt3.x) * (pt1.y - pt3.y) def iswithin(point, pt1, pt2, pt3): zval1 = sign(point, pt1, pt2) zval2 = sign(point, pt2, pt3) zval3 = sign(point, pt3, pt1) notanyneg = zval1 >= 0 and zval2 >= 0 and zval3 >= 0 notanypos = zval1 <= 0 and zval2 <= 0 and zval3 <= 0 return notanyneg or notanypos if __name__ == : POINTS = [Point(0, 0)] TRI = Triangle(Point(1.5, 2.4), Point(5.1, -3.1), Point(-3.8, 0.5)) for pnt in POINTS: a, b, c = TRI.vertices isornot = if iswithin(pnt, a, b, c) else print(, pnt, isornot, , TRI)
839Find if a point is within a triangle
3python
06qsq
def recurse; recurse = { try { recurse (it + 1) } catch (StackOverflowError e) { return it } } recurse(0)
841Find limit of recursion
7groovy
jq47o
import Debug.Trace (trace) recurse :: Int -> Int recurse n = trace (show n) recurse (succ n) main :: IO () main = print $ recurse 1
841Find limit of recursion
8haskell
tvif7
int checkFileExtension(char* fileName, char* fileExtensions) { char* fileExtension = fileExtensions; if ( *fileName ) { while ( *fileExtension ) { int fileNameLength = strlen(fileName); int extensionLength = strlen(fileExtension); if ( fileNameLength >= extensionLength ) { char* a = fileName + fileNameLength - extensionLength; char* b = fileExtension; while ( *a && toupper(*a++) == toupper(*b++) ) ; if ( !*a ) return true; } fileExtension += extensionLength + 1; } } return false; } void printExtensions(char* extensions) { while( *extensions ) { printf(, extensions); extensions += strlen(extensions) + 1; } } bool test(char* fileName, char* extension, bool expectedResult) { bool result = checkFileExtension(fileName,extension); bool returnValue = result == expectedResult; printf(, fileName, result ? : , expectedResult ? : , returnValue ? : ); return returnValue; } int main(void) { static char extensions[] = ; setlocale(LC_ALL,); printExtensions(extensions); printf(); if ( test(, extensions,true ) && test(, extensions,true ) && test(, extensions,false) && test(, extensions,false) && test(, extensions,false) && test(, extensions,false) && test(,extensions,true ) && test(, extensions,false) && test(, extensions,false) ) printf(, ); else printf(, ); printf(, ); getchar(); return 0; }
847File extension is in extensions list
5c
jqc70
from itertools import islice digits = def baseN(num,b): if num == 0: return result = while num != 0: num, d = divmod(num, b) result += digits[d] return result[::-1] def pal2(num): if num == 0 or num == 1: return True based = bin(num)[2:] return based == based[::-1] def pal_23(): yield 0 yield 1 n = 1 while True: n += 1 b = baseN(n, 3) revb = b[::-1] for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb), '{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)): t = int(trial, 3) if pal2(t): yield t for pal23 in islice(pal_23(), 6): print(pal23, baseN(pal23, 3), baseN(pal23, 2))
840Find palindromic numbers in both binary and ternary bases
3python
oms81
(require '[clojure.java.io:as io]) (defn show-size [filename] (println filename "size:" (.length (io/file filename)))) (show-size "input.txt") (show-size "/input.txt")
845File size
6clojure
ge94f
use std::error::Error; use std::marker::PhantomData; use std::path::{Path, PathBuf}; use std::{env, fmt, io, time}; use walkdir::{DirEntry, WalkDir}; fn main() -> Result<(), Box<dyn Error>> { let start = time::Instant::now(); let args: Vec<String> = env::args().collect(); let root = parse_path(&args).expect("not a valid path"); let dir = WalkDir::new(&root); let (files, dirs): (Vec<PathBuf>, Vec<PathBuf>) = { let pool = pool(dir).expect("unable to retrieve entries from WalkDir"); partition_from(pool).expect("unable to partition files from directories") }; let (fs_count, dr_count) = (files.len(), dirs.len()); let (file_counter, total_size) = file_count(files); { println!("++ File size distribution for: {} ++\n", &root.display()); println!("Files @ 0B : {:4}", file_counter[0]); println!("Files > 1B - 1,023B : {:4}", file_counter[1]); println!("Files > 1KB - 1,023KB: {:4}", file_counter[2]); println!("Files > 1MB - 1,023MB: {:4}", file_counter[3]); println!("Files > 1GB - 1,023GB: {:4}", file_counter[4]); println!("Files > 1TB+ : {:4}\n", file_counter[5]); println!("Files encountered: {}", fs_count); println!("Directories traversed: {}", dr_count); println!( "Total size of all files: {}\n", Filesize::<Kilobytes>::from(total_size) ); } let end = time::Instant::now(); println!("Run time: {:?}\n", end.duration_since(start)); Ok(()) } fn parse_path(args: &[String]) -> Result<&Path, io::Error> {
842File size distribution
15rust
hs4j2
(defn matches-extension [ext s] (re-find (re-pattern (str "\\." ext "$")) (clojure.string/lower-case s))) (defn matches-extension-list [ext-list s] (some #(matches-extension % s) ext-list))
847File extension is in extensions list
6clojure
1i5py
EPS = 0.001 EPS_SQUARE = EPS * EPS def side(x1, y1, x2, y2, x, y) return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1) end def naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) checkSide1 = side(x1, y1, x2, y2, x, y) >= 0 checkSide2 = side(x2, y2, x3, y3, x, y) >= 0 checkSide3 = side(x3, y3, x1, y1, x, y) >= 0 return checkSide1 && checkSide2 && checkSide3 end def pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) xMin = [x1, x2, x3].min - EPS xMax = [x1, x2, x3].max + EPS yMin = [y1, y2, y3].min - EPS yMax = [y1, y2, y3].max + EPS return!(x < xMin || xMax < x || y < yMin || yMax < y) end def distanceSquarePointToSegment(x1, y1, x2, y2, x, y) p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1) dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength if dotProduct < 0 then return (x - x1) * (x - x1) + (y - y1) * (y - y1) end if dotProduct <= 1 then p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y) return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength end return (x - x2) * (x - x2) + (y - y2) * (y - y2) end def accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) if!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) then return false end if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) then return true end if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE then return true end if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE then return true end if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE then return true end return false end def main pts = [[0, 0], [0, 1], [3, 1]] tri = [[1.5, 2.4], [5.1, -3.1], [-3.8, 1.2]] print , tri, x1, y1 = tri[0][0], tri[0][1] x2, y2 = tri[1][0], tri[1][1] x3, y3 = tri[2][0], tri[2][1] for pt in pts x, y = pt[0], pt[1] within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) print , pt, , within, end print tri = [[0.1, 1.0 / 9.0], [12.5, 100.0 / 3.0], [25.0, 100.0 / 9.0]] print , tri, x1, y1 = tri[0][0], tri[0][1] x2, y2 = tri[1][0], tri[1][1] x3, y3 = tri[2][0], tri[2][1] x = x1 + (3.0 / 7.0) * (x2 - x1) y = y1 + (3.0 / 7.0) * (y2 - y1) pt = [x, y] within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) print , pt, , within, print tri = [[0.1, 1.0 / 9.0], [12.5, 100.0 / 3.0], [-12.5, 100.0 / 6.0]] print , tri, x3, y3 = tri[2][0], tri[2][1] within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) print , pt, , within, end main()
839Find if a point is within a triangle
14ruby
om08v
package main import ( "fmt" "os" "syscall" "time" ) var filename = "input.txt" func main() { foo, err := os.Stat(filename) if err != nil { fmt.Println(err) return } fmt.Println("mod time was:", foo.ModTime()) mtime := time.Now() atime := mtime
844File modification time
0go
i9wog
public class RecursionTest { private static void recurse(int i) { try { recurse(i+1); } catch (StackOverflowError e) { System.out.print("Recursion depth on this system is " + i + "."); } } public static void main(String[] args) { recurse(0); } }
841Find limit of recursion
9java
8yx06
function recurse(depth) { try { return recurse(depth + 1); } catch(ex) { return depth; } } var maxRecursion = recurse(1); document.write("Recursion depth on this system is " + maxRecursion);
841Find limit of recursion
10javascript
f2odg
pal23 = Enumerator.new do |y| y << 0 y << 1 for i in 1 .. 1.0/0.0 n3 = i.to_s(3) n = (n3 + + n3.reverse).to_i(3) n2 = n.to_s(2) y << n if n2.size.odd? and n2 == n2.reverse end end puts 6.times do |i| n = pal23.next puts % [i, n, n.to_s(3).center(25), n.to_s(2).center(39)] end
840Find palindromic numbers in both binary and ternary bases
14ruby
nc8it
import System.Posix.Files import System.Posix.Time do status <- getFileStatus filename let atime = accessTime status mtime = modificationTime status curTime <- epochTime setFileTimes filename atime curTime
844File modification time
8haskell
vb62k
package main import ( "fmt" "os" "path" ) func CommonPrefix(sep byte, paths ...string) string {
843Find common directory path
0go
06ask
import scala.annotation.tailrec import scala.compat.Platform.currentTime object Palindrome23 extends App { private val executionStartTime = currentTime private val st: Stream[(Int, Long)] = (0, 1L) #:: st.map(xs => nextPalin3(xs._1)) @tailrec private def nextPalin3(n: Int): (Int, Long) = { @inline def isPali2(i: BigInt): Boolean = { val s = i.toString(2) if ((s.length & 1) == 0) false else s == s.reverse } def palin3(i: BigInt): Long = { val n3 = i.toString(3) java.lang.Long.parseLong(n3 + "1" + n3.reverse, 3) } val actual: Long = palin3(n) if (isPali2(actual)) (n + 1, actual) else nextPalin3(n + 1) } println(f"${"Decimal"}%18s${"Binary"}%35s${"Ternary"}%51s") (Stream(0L) ++ st.map(_._2)).take(6).foreach(n => { val bigN = BigInt(n) val (bin, ter) = (bigN.toString(2), bigN.toString(3)) println(f"${n}%18d, ${ bin + " " * ((60 - bin.length) / 2)}%60s, ${ ter + " " * ((37 - ter.length) / 2)}%37s") }) println(s"Successfully completed without errors. [total ${currentTime - executionStartTime} ms]") }
840Find palindromic numbers in both binary and ternary bases
16scala
zudtr
package main import ( "fmt" "strings" ) var extensions = []string{"zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"} func fileExtInList(filename string) (bool, string) { filename2 := strings.ToLower(filename) for _, ext := range extensions { ext2 := "." + strings.ToLower(ext) if strings.HasSuffix(filename2, ext2) { return true, ext } } s := strings.Split(filename, ".") if len(s) > 1 { t := s[len(s)-1] if t != "" { return false, t } else { return false, "<empty>" } } else { return false, "<none>" } } func main() { fmt.Println("The listed extensions are:") fmt.Println(extensions, "\n") tests := []string{ "MyData.a##", "MyData.tar.Gz", "MyData.gzip", "MyData.7z.backup", "MyData...", "MyData", "MyData_v1.0.tar.bz2", "MyData_v1.0.bz2", } for _, test := range tests { ok, ext := fileExtInList(test) fmt.Printf("%-20s =>%-5t (extension =%s)\n", test, ok, ext) } }
847File extension is in extensions list
0go
f2wd0
package main import ( "github.com/fogleman/gg" "strings" ) func wordFractal(i int) string { if i < 2 { if i == 1 { return "1" } return "" } var f1 strings.Builder f1.WriteString("1") var f2 strings.Builder f2.WriteString("0") for j := i - 2; j >= 1; j-- { tmp := f2.String() f2.WriteString(f1.String()) f1.Reset() f1.WriteString(tmp) } return f2.String() } func draw(dc *gg.Context, x, y, dx, dy float64, wf string) { for i, c := range wf { dc.DrawLine(x, y, x+dx, y+dy) x += dx y += dy if c == '0' { tx := dx dx = dy if i%2 == 0 { dx = -dy } dy = -tx if i%2 == 0 { dy = tx } } } } func main() { dc := gg.NewContext(450, 620) dc.SetRGB(0, 0, 0) dc.Clear() wf := wordFractal(23) draw(dc, 20, 20, 1, 0, wf) dc.SetRGB(0, 1, 0) dc.SetLineWidth(1) dc.Stroke() dc.SavePNG("fib_wordfractal.png") }
846Fibonacci word/fractal
0go
rw9gm
def commonPath = { delim, Object[] paths -> def pathParts = paths.collect { it.split(delim) } pathParts.transpose().inject([match:true, commonParts:[]]) { aggregator, part -> aggregator.match = aggregator.match && part.every { it == part [0] } if (aggregator.match) { aggregator.commonParts << part[0] } aggregator }.commonParts.join(delim) }
843Find common directory path
7groovy
edhal
null
841Find limit of recursion
11kotlin
wfpek
void feigenbaum() { int i, j, k, max_it = 13, max_it_j = 10; double a, x, y, d, a1 = 1.0, a2 = 0.0, d1 = 3.2; printf(); for (i = 2; i <= max_it; ++i) { a = a1 + (a1 - a2) / d1; for (j = 1; j <= max_it_j; ++j) { x = 0.0; y = 0.0; for (k = 1; k <= 1 << i; ++k) { y = 1.0 - 2.0 * y * x; x = a - x * x; } a -= x / y; } d = (a1 - a2) / (a - a1); printf(, i, d); d1 = d; a2 = a1; a1 = a; } } int main() { feigenbaum(); return 0; }
848Feigenbaum constant calculation
5c
an511
import Data.List import qualified Data.Char as Ch toLower :: String -> String toLower = map Ch.toLower isExt :: String -> [String] -> Bool isExt filename extensions = any (`elem` (tails . toLower $ filename)) $ map toLower extensions
847File extension is in extensions list
8haskell
4a65s
import java.io.File; import java.util.Date; public class FileModificationTimeTest { public static void test(String type, File file) { long t = file.lastModified(); System.out.println("The following " + type + " called " + file.getPath() + (t == 0 ? " does not exist." : " was modified at " + new Date(t).toString() ) ); System.out.println("The following " + type + " called " + file.getPath() + (!file.setLastModified(System.currentTimeMillis()) ? " does not exist." : " was modified to current time." ) ); System.out.println("The following " + type + " called " + file.getPath() + (!file.setLastModified(t) ? " does not exist." : " was modified to previous time." ) ); } public static void main(String args[]) { test("file", new File("output.txt")); test("directory", new File("docs")); } }
844File modification time
9java
ygn6g
var fso = new ActiveXObject("Scripting.FileSystemObject"); var f = fso.GetFile('input.txt'); var mtime = f.DateLastModified;
844File modification time
10javascript
2k3lr
import Foundation func isPalin2(n: Int) -> Bool { var x = 0 var n = n guard n & 1!= 0 else { return n == 0 } while x < n { x = x << 1 | n & 1 n >>= 1 } return n == x || n == x >> 1 } func reverse3(n: Int) -> Int { var x = 0 var n = n while n > 0 { x = x * 3 + (n% 3) n /= 3 } return x } func printN(_ n: Int, base: Int) { var n = n print(" ", terminator: "") repeat { print("\(n% base)", terminator: "") n /= base } while n > 0 print("(\(base))", terminator: "") } func show(n: Int) { print(n, terminator: "") printN(n, base: 2) printN(n, base: 3) print() } private var count = 0 private var lo = 0 private var (hi, pow2, pow3) = (1, 1, 1) show(n: 0) while true { var n: Int for i in lo..<hi { n = (i * 3 + 1) * pow3 + reverse3(n: i) guard isPalin2(n: n) else { continue } show(n: n) count += 1 guard count < 7 else { exit(0) } } if hi == pow3 { pow3 *= 3 } else { pow2 *= 4 } while true { while pow2 <= pow3 { pow2 *= 4 } let lo2 = (pow2 / pow3 - 1) / 3 let hi2 = (pow2 * 2 / pow3 - 1) / 3 + 1 let lo3 = pow3 / 3 let hi3 = pow3 if lo2 >= hi3 { pow3 *= 3 } else if lo3 >= hi2 { pow2 *= 4 } else { lo = max(lo2, lo3) hi = min(hi2, hi3) break } } }
840Find palindromic numbers in both binary and ternary bases
17swift
i90o0
gcc -o fermat fermat.c -lgmp
849Fermat numbers
5c
i9bo2
import java.util.Arrays; import java.util.Comparator; public class FileExt{ public static void main(String[] args){ String[] tests = {"text.txt", "text.TXT", "test.tar.gz", "test/test2.exe", "test\\test2.exe", "test", "a/b/c\\d/foo"}; String[] exts = {".txt",".gz","",".bat"}; System.out.println("Extensions: " + Arrays.toString(exts) + "\n"); for(String test:tests){ System.out.println(test +": " + extIsIn(test, exts)); } } public static boolean extIsIn(String test, String... exts){ int lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\'));
847File extension is in extensions list
9java
cjn9h
import Data.List (unfoldr) import Data.Bool (bool) import Data.Semigroup (Sum(..), Min(..), Max(..)) import System.IO (writeFile) fibonacciWord :: a -> a -> [[a]] fibonacciWord a b = unfoldr (\(a,b) -> Just (a, (b, a <> b))) ([a], [b]) toPath :: [Bool] -> ((Min Int, Max Int, Min Int, Max Int), String) toPath = foldMap (\p -> (box p, point p)) . scanl (<>) mempty . scanl (\dir (turn, s) -> bool dir (turn dir) s) (1, 0) . zip (cycle [left, right]) where box (Sum x, Sum y) = (Min x, Max x, Min y, Max y) point (Sum x, Sum y) = show x ++ "," ++ show y ++ " " left (x,y) = (-y, x) right (x,y) = (y, -x) toSVG :: [Bool] -> String toSVG w = let ((Min x1, Max x2, Min y1, Max y2), path) = toPath w in unwords [ "<svg xmlns='http://www.w3.org/2000/svg'" , "width='500' height='500'" , "stroke='black' fill='none' strokeWidth='2'" , "viewBox='" ++ unwords (show <$> [x1,y1,x2-x1,y2-y1]) ++ "'>" , "<polyline points='" ++ path ++ "'/>" , "</svg>"] main = writeFile "test.html" $ toSVG $ fibonacciWord True False !! 21
846Fibonacci word/fractal
8haskell
06bs7
import Data.List commonPrefix2 (x:xs) (y:ys) | x == y = x: commonPrefix2 xs ys commonPrefix2 _ _ = [] commonPrefix (xs:xss) = foldr commonPrefix2 xs xss commonPrefix _ = [] splitPath = groupBy (\_ c -> c /= '/') commonDirPath = concat . commonPrefix . map splitPath main = putStrLn $ commonDirPath [ "/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members" ]
843Find common directory path
8haskell
cjz94
local c = 0 function Tail(proper) c = c + 1 if proper then if c < 9999999 then return Tail(proper) else return c end else return 1/c+Tail(proper)
841Find limit of recursion
1lua
xt1wz
int main(int argc, char **argv) { FILE *in, *out; int c; in = fopen(, ); if (!in) { fprintf(stderr, ); return 1; } out = fopen(, ); if (!out) { fprintf(stderr, ); fclose(in); return 1; } while ((c = fgetc(in)) != EOF) { fputc(c, out); } fclose(out); fclose(in); return 0; }
850File input/output
5c
vbn2o
void print_headings() { printf(, ); printf(, ); printf(, ); printf(, ); printf(); } double calculate_entropy(int ones, int zeros) { double result = 0; int total = ones + zeros; result -= (double) ones / total * log2((double) ones / total); result -= (double) zeros / total * log2((double) zeros / total); if (result != result) { result = 0; } return result; } void print_entropy(char *word) { int ones = 0; int zeros = 0; int i; for (i = 0; word[i]; i++) { char c = word[i]; switch (c) { case '0': zeros++; break; case '1': ones++; break; } } double entropy = calculate_entropy(ones, zeros); printf(, entropy); } void print_word(int n, char *word) { printf(, n); printf(, strlen(word)); print_entropy(word); if (n < 10) { printf(, word); } else { printf(, ); } printf(); } int main(int argc, char *argv[]) { print_headings(); char *last_word = malloc(2); strcpy(last_word, ); char *current_word = malloc(2); strcpy(current_word, ); print_word(1, last_word); int i; for (i = 2; i <= 37; i++) { print_word(i, current_word); char *next_word = malloc(strlen(current_word) + strlen(last_word) + 1); strcpy(next_word, current_word); strcat(next_word, last_word); free(last_word); last_word = current_word; current_word = next_word; } free(last_word); free(current_word); return 0; }
851Fibonacci word
5c
97sm1
null
844File modification time
11kotlin
f2sdo
require "lfs" local attributes = lfs.attributes("input.txt") if attributes then print(path .. " was last modified " .. os.date("%c", attributes.modification) .. ".")
844File modification time
1lua
tv0fn
import java.awt.*; import javax.swing.*; public class FibonacciWordFractal extends JPanel { String wordFractal; FibonacciWordFractal(int n) { setPreferredSize(new Dimension(450, 620)); setBackground(Color.white); wordFractal = wordFractal(n); } public String wordFractal(int n) { if (n < 2) return n == 1 ? "1" : "";
846Fibonacci word/fractal
9java
ang1y
package main import ( "fmt" "github.com/jbarham/primegen" "math" "math/big" "math/rand" "sort" "time" ) const ( maxCurves = 10000 maxRnd = 1 << 31 maxB1 = uint64(43 * 1e7) maxB2 = uint64(2 * 1e10) ) var ( zero = big.NewInt(0) one = big.NewInt(1) two = big.NewInt(2) three = big.NewInt(3) four = big.NewInt(4) five = big.NewInt(5) )
849Fermat numbers
0go
ge34n
null
847File extension is in extensions list
11kotlin
35sz5
null
847File extension is in extensions list
1lua
64039
null
846Fibonacci word/fractal
10javascript
s3kqz
public class CommonPath { public static String commonPath(String... paths){ String commonPath = ""; String[][] folders = new String[paths.length][]; for(int i = 0; i < paths.length; i++){ folders[i] = paths[i].split("/");
843Find common directory path
9java
zuotq
(use 'clojure.java.io) (copy (file "input.txt") (file "output.txt"))
850File input/output
6clojure
rw3g2
import Data.Numbers.Primes (primeFactors) import Data.Bool (bool) fermat :: Integer -> Integer fermat = succ . (2 ^) . (2 ^) fermats :: [Integer] fermats = fermat <$> [0 ..] main :: IO () main = mapM_ putStrLn [ fTable "First 10 Fermats:" show show fermat [0 .. 9] , fTable "Factors of first 7:" show showFactors primeFactors (take 7 fermats) ] fTable :: String -> (a -> String) -> (b -> String) -> (a -> b) -> [a] -> String fTable s xShow fxShow f xs = unlines $ s: fmap (((++) . rjust w ' ' . xShow) <*> ((" -> " ++) . fxShow . f)) xs where rjust n c = drop . length <*> (replicate n c ++) w = maximum (length . xShow <$> xs) showFactors :: [Integer] -> String showFactors x | 1 < length x = show x | otherwise = "(prime)"
849Fermat numbers
8haskell
s37qk
package main import "fmt" func feigenbaum() { maxIt, maxItJ := 13, 10 a1, a2, d1 := 1.0, 0.0, 3.2 fmt.Println(" i d") for i := 2; i <= maxIt; i++ { a := a1 + (a1-a2)/d1 for j := 1; j <= maxItJ; j++ { x, y := 0.0, 0.0 for k := 1; k <= 1<<uint(i); k++ { y = 1.0 - 2.0*y*x x = a - x*x } a -= x / y } d := (a1 - a2) / (a - a1) fmt.Printf("%2d %.8f\n", i, d) d1, a2, a1 = d, a1, a } } func main() { feigenbaum() }
848Feigenbaum constant calculation
0go
mr8yi
null
846Fibonacci word/fractal
11kotlin
hs2j3
const splitStrings = (a, sep = '/') => a.map(i => i.split(sep)); const elAt = i => a => a[i]; const rotate = a => a[0].map((e, i) => a.map(elAt(i))); const allElementsEqual = arr => arr.every(e => e === arr[0]); const commonPath = (input, sep = '/') => rotate(splitStrings(input, sep)) .filter(allElementsEqual).map(elAt(0)).join(sep); const cdpInput = [ '/home/user1/tmp/coverage/test', '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members', ]; console.log(`Common path is: ${commonPath(cdpInput)}`);
843Find common directory path
10javascript
97tml
package main import "fmt" import "os" func printFileSize(f string) { if stat, err := os.Stat(f); err != nil { fmt.Println(err) } else { fmt.Println(stat.Size()) } } func main() { printFileSize("input.txt") printFileSize("/input.txt") }
845File size
0go
qzkxz
println new File('index.txt').length(); println new File('/index.txt').length();
845File size
7groovy
1igp6
(defn entropy [s] (let [len (count s), log-2 (Math/log 2)] (->> (frequencies s) (map (fn [[_ v]] (let [rf (/ v len)] (-> (Math/log rf) (/ log-2) (* rf) Math/abs)))) (reduce +)))) (defn fibonacci [cat a b] (lazy-seq (cons a (fibonacci b (cat a b))))) (printf "%2s%10s%17s%s%n" "N" "Length" "Entropy" "Fibword") (doseq [i (range 1 38) w (take 37 (fibonacci str "1" "0"))] (printf "%2d%10d%.15f%s%n" i (count w) (entropy w) (if (<= i 8) w "..."))))
851Fibonacci word
6clojure
upnvi
import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class FermatNumbers { public static void main(String[] args) { System.out.println("First 10 Fermat numbers:"); for ( int i = 0 ; i < 10 ; i++ ) { System.out.printf("F[%d] =%s\n", i, fermat(i)); } System.out.printf("%nFirst 12 Fermat numbers factored:%n"); for ( int i = 0 ; i < 13 ; i++ ) { System.out.printf("F[%d] =%s\n", i, getString(getFactors(i, fermat(i)))); } } private static String getString(List<BigInteger> factors) { if ( factors.size() == 1 ) { return factors.get(0) + " (PRIME)"; } return factors.stream().map(v -> v.toString()).map(v -> v.startsWith("-") ? "(C" + v.replace("-", "") + ")" : v).collect(Collectors.joining(" * ")); } private static Map<Integer, String> COMPOSITE = new HashMap<>(); static { COMPOSITE.put(9, "5529"); COMPOSITE.put(10, "6078"); COMPOSITE.put(11, "1037"); COMPOSITE.put(12, "5488"); COMPOSITE.put(13, "2884"); } private static List<BigInteger> getFactors(int fermatIndex, BigInteger n) { List<BigInteger> factors = new ArrayList<>(); BigInteger factor = BigInteger.ONE; while ( true ) { if ( n.isProbablePrime(100) ) { factors.add(n); break; } else { if ( COMPOSITE.containsKey(fermatIndex) ) { String stop = COMPOSITE.get(fermatIndex); if ( n.toString().startsWith(stop) ) { factors.add(new BigInteger("-" + n.toString().length())); break; } } factor = pollardRhoFast(n); if ( factor.compareTo(BigInteger.ZERO) == 0 ) { factors.add(n); break; } else { factors.add(factor); n = n.divide(factor); } } } return factors; } private static final BigInteger TWO = BigInteger.valueOf(2); private static BigInteger fermat(int n) { return TWO.pow((int)Math.pow(2, n)).add(BigInteger.ONE); }
849Fermat numbers
9java
1ivp2
class Feigenbaum { static void main(String[] args) { int max_it = 13 int max_it_j = 10 double a1 = 1.0 double a2 = 0.0 double d1 = 3.2 double a println(" i d") for (int i = 2; i <= max_it; i++) { a = a1 + (a1 - a2) / d1 for (int j = 0; j < max_it_j; j++) { double x = 0.0 double y = 0.0 for (int k = 0; k < 1 << i; k++) { y = 1.0 - 2.0 * y * x x = a - x * x } a -= x / y } double d = (a1 - a2) / (a - a1) printf("%2d %.8f\n", i, d) d1 = d a2 = a1 a1 = a } } }
848Feigenbaum constant calculation
7groovy
tvwfh
import Data.List (mapAccumL) feigenbaumApprox :: Int -> [Double] feigenbaumApprox mx = snd $ mitch mx 10 where mitch :: Int -> Int -> ((Double, Double, Double), [Double]) mitch mx mxj = mapAccumL (\(a1, a2, d1) i -> let a = iterate (\a -> let (x, y) = iterate (\(x, y) -> (a - (x * x), 1.0 - ((2.0 * x) * y))) (0.0, 0.0) !! (2 ^ i) in a - (x / y)) (a1 + (a1 - a2) / d1) !! mxj d = (a1 - a2) / (a - a1) in ((a, a1, d), d)) (1.0, 0.0, 3.2) [2 .. (1 + mx)] main :: IO () main = (putStrLn . unlines) $ zipWith (\i s -> justifyRight 2 ' ' (show i) ++ '\t': s) [1 ..] (show <$> feigenbaumApprox 13) where justifyRight n c s = drop (length s) (replicate n c ++ s)
848Feigenbaum constant calculation
8haskell
k0lh0
RIGHT, LEFT, UP, DOWN = 1, 2, 4, 8 function drawFractals( w ) love.graphics.setCanvas( canvas ) love.graphics.clear() love.graphics.setColor( 255, 255, 255 ) local dir, facing, lineLen, px, py, c = RIGHT, UP, 1, 10, love.graphics.getHeight() - 20, 1 local x, y = 0, -lineLen local pts = {} table.insert( pts, px + .5 ); table.insert( pts, py + .5 ) for i = 1, #w do px = px + x; table.insert( pts, px + .5 ) py = py + y; table.insert( pts, py + .5 ) if w:sub( i, i ) == "0" then if c % 2 == 1 then dir = RIGHT else dir = LEFT end if facing == UP then if dir == RIGHT then x = lineLen; facing = RIGHT else x = -lineLen; facing = LEFT end; y = 0 elseif facing == RIGHT then if dir == RIGHT then y = lineLen; facing = DOWN else y = -lineLen; facing = UP end; x = 0 elseif facing == DOWN then if dir == RIGHT then x = -lineLen; facing = LEFT else x = lineLen; facing = RIGHT end; y = 0 elseif facing == LEFT then if dir == RIGHT then y = -lineLen; facing = UP else y = lineLen; facing = DOWN end; x = 0 end end c = c + 1 end love.graphics.line( pts ) love.graphics.setCanvas() end function createWord( wordLen ) local a, b, w = "1", "0" repeat w = b .. a; a = b; b = w; wordLen = wordLen - 1 until wordLen == 0 return w end function love.load() wid, hei = love.graphics.getWidth(), love.graphics.getHeight() canvas = love.graphics.newCanvas( wid, hei ) drawFractals( createWord( 21 ) ) end function love.draw() love.graphics.draw( canvas ) end
846Fibonacci word/fractal
1lua
k0vh2
import System.IO printFileSize filename = withFile filename ReadMode hFileSize >>= print main = mapM_ printFileSize ["input.txt", "/input.txt"]
845File size
8haskell
mrnyf
int binomial(int n, int k) { int num, denom, i; if (n < 0 || k < 0 || n < k) return -1; if (n == 0 || k == 0) return 1; num = 1; for (i = k + 1; i <= n; ++i) { num = num * i; } denom = 1; for (i = 2; i <= n - k; ++i) { denom *= i; } return num / denom; } int gcd(int a, int b) { int temp; while (b != 0) { temp = a % b; a = b; b = temp; } return a; } typedef struct tFrac { int num, denom; } Frac; Frac makeFrac(int n, int d) { Frac result; int g; if (d == 0) { result.num = 0; result.denom = 0; return result; } if (n == 0) { d = 1; } else if (d < 0) { n = -n; d = -d; } g = abs(gcd(n, d)); if (g > 1) { n = n / g; d = d / g; } result.num = n; result.denom = d; return result; } Frac negateFrac(Frac f) { return makeFrac(-f.num, f.denom); } Frac subFrac(Frac lhs, Frac rhs) { return makeFrac(lhs.num * rhs.denom - lhs.denom * rhs.num, rhs.denom * lhs.denom); } Frac multFrac(Frac lhs, Frac rhs) { return makeFrac(lhs.num * rhs.num, lhs.denom * rhs.denom); } bool equalFrac(Frac lhs, Frac rhs) { return (lhs.num == rhs.num) && (lhs.denom == rhs.denom); } bool lessFrac(Frac lhs, Frac rhs) { return (lhs.num * rhs.denom) < (rhs.num * lhs.denom); } void printFrac(Frac f) { printf(, f.num); if (f.denom != 1) { printf(, f.denom); } } Frac bernoulli(int n) { Frac a[16]; int j, m; if (n < 0) { a[0].num = 0; a[0].denom = 0; return a[0]; } for (m = 0; m <= n; ++m) { a[m] = makeFrac(1, m + 1); for (j = m; j >= 1; --j) { a[j - 1] = multFrac(subFrac(a[j - 1], a[j]), makeFrac(j, 1)); } } if (n != 1) { return a[0]; } return negateFrac(a[0]); } void faulhaber(int p) { Frac coeff, q; int j, pwr, sign; printf(, p); q = makeFrac(1, p + 1); sign = -1; for (j = 0; j <= p; ++j) { sign = -1 * sign; coeff = multFrac(multFrac(multFrac(q, makeFrac(sign, 1)), makeFrac(binomial(p + 1, j), 1)), bernoulli(j)); if (equalFrac(coeff, makeFrac(0, 1))) { continue; } if (j == 0) { if (!equalFrac(coeff, makeFrac(1, 1))) { if (equalFrac(coeff, makeFrac(-1, 1))) { printf(); } else { printFrac(coeff); } } } else { if (equalFrac(coeff, makeFrac(1, 1))) { printf(); } else if (equalFrac(coeff, makeFrac(-1, 1))) { printf(); } else if (lessFrac(makeFrac(0, 1), coeff)) { printf(); printFrac(coeff); } else { printf(); printFrac(negateFrac(coeff)); } } pwr = p + 1 - j; if (pwr > 1) { printf(, pwr); } else { printf(); } } printf(); } int main() { int i; for (i = 0; i < 10; ++i) { faulhaber(i); } return 0; }
852Faulhaber's formula
5c
mrxys
public class Feigenbaum { public static void main(String[] args) { int max_it = 13; int max_it_j = 10; double a1 = 1.0; double a2 = 0.0; double d1 = 3.2; double a; System.out.println(" i d"); for (int i = 2; i <= max_it; i++) { a = a1 + (a1 - a2) / d1; for (int j = 0; j < max_it_j; j++) { double x = 0.0; double y = 0.0; for (int k = 0; k < 1 << i; k++) { y = 1.0 - 2.0 * y * x; x = a - x * x; } a -= x / y; } double d = (a1 - a2) / (a - a1); System.out.printf("%2d %.8f\n", i, d); d1 = d; a2 = a1; a1 = a; } } }
848Feigenbaum constant calculation
9java
4a358
null
843Find common directory path
11kotlin
i9xo4
int even_sel(int x) { return !(x & 1); } int tri_sel(int x) { return x % 3; } int* grep(int *in, int len, int *outlen, int (*sel)(int), int inplace) { int i, j, *out; if (inplace) out = in; else out = malloc(sizeof(int) * len); for (i = j = 0; i < len; i++) if (sel(in[i])) out[j++] = in[i]; if (!inplace && j < len) out = realloc(out, sizeof(int) * j); *outlen = j; return out; } int main() { int in[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int i, len; int *even = grep(in, 10, &len, even_sel, 0); printf(); for (i = 0; i < len; i++) printf(, even[i]); printf(); grep(in, 8, &len, tri_sel, 1); printf(); for (i = 0; i < len; i++) printf(, in[i]); printf(); return 0; }
853Filter
5c
4an5t
import java.io.File; public class FileSize { public static void main ( String[] args ) { System.out.println("input.txt : " + new File("input.txt").length() + " bytes"); System.out.println("/input.txt: " + new File("/input.txt").length() + " bytes"); } }
845File size
9java
f2qdv
void main() { FILE * fp; char * line = NULL; size_t len = 0; ssize_t read; fp = fopen(, ); if (fp == NULL) exit(EXIT_FAILURE); int state = 0; while ((read = getline(&line, &len, fp)) != -1) { if (line[read - 1] == '\n') line[read - 1] = 0; if (line[0] == '>') { if (state == 1) printf(); printf(, line+1); state = 1; } else { printf(, line); } } printf(); fclose(fp); if (line) free(line); exit(EXIT_SUCCESS); }
854FASTA format
5c
51ouk
import java.math.BigInteger import kotlin.math.pow fun main() { println("First 10 Fermat numbers:") for (i in 0..9) { println("F[$i] = ${fermat(i)}") } println() println("First 12 Fermat numbers factored:") for (i in 0..12) { println("F[$i] = ${getString(getFactors(i, fermat(i)))}") } } private fun getString(factors: List<BigInteger>): String { return if (factors.size == 1) { "${factors[0]} (PRIME)" } else factors.map { it.toString() } .joinToString(" * ") { if (it.startsWith("-")) "(C" + it.replace("-", "") + ")" else it } } private val COMPOSITE = mutableMapOf( 9 to "5529", 10 to "6078", 11 to "1037", 12 to "5488", 13 to "2884" ) private fun getFactors(fermatIndex: Int, n: BigInteger): List<BigInteger> { var n2 = n val factors: MutableList<BigInteger> = ArrayList() var factor: BigInteger while (true) { if (n2.isProbablePrime(100)) { factors.add(n2) break } else { if (COMPOSITE.containsKey(fermatIndex)) { val stop = COMPOSITE[fermatIndex] if (n2.toString().startsWith(stop!!)) { factors.add(BigInteger("-" + n2.toString().length)) break } }
849Fermat numbers
11kotlin
jqm7r
null
848Feigenbaum constant calculation
11kotlin
lhncp
sub check_extension { my ($filename, @extensions) = @_; my $extensions = join '|', map quotemeta, @extensions; scalar $filename =~ / \. (?: $extensions ) $ /xi }
847File extension is in extensions list
2perl
poub0
$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A $lc_allowed = array_map('strtolower', $allowed); $tests = [ ['MyData.a ['MyData.tar.Gz',true], ['MyData.gzip',false], ['MyData.7z.backup',false], ['MyData...',false], ['MyData',false], ['archive.tar.gz', true] ]; foreach ($tests as $test) { $ext = pathinfo($test[0], PATHINFO_EXTENSION); if (in_array(strtolower($ext), $lc_allowed)) { $result = 'true'; } else { $result = 'false'; } printf(, $test[0],$result); }
847File extension is in extensions list
12php
yg861
var fso = new ActiveXObject("Scripting.FileSystemObject"); fso.GetFile('input.txt').Size; fso.GetFile('c:/input.txt').Size;
845File size
10javascript
ygi6r
int binomial(int n, int k) { int num, denom, i; if (n < 0 || k < 0 || n < k) return -1; if (n == 0 || k == 0) return 1; num = 1; for (i = k + 1; i <= n; ++i) { num = num * i; } denom = 1; for (i = 2; i <= n - k; ++i) { denom *= i; } return num / denom; } int gcd(int a, int b) { int temp; while (b != 0) { temp = a % b; a = b; b = temp; } return a; } typedef struct tFrac { int num, denom; } Frac; Frac makeFrac(int n, int d) { Frac result; int g; if (d == 0) { result.num = 0; result.denom = 0; return result; } if (n == 0) { d = 1; } else if (d < 0) { n = -n; d = -d; } g = abs(gcd(n, d)); if (g > 1) { n = n / g; d = d / g; } result.num = n; result.denom = d; return result; } Frac negateFrac(Frac f) { return makeFrac(-f.num, f.denom); } Frac subFrac(Frac lhs, Frac rhs) { return makeFrac(lhs.num * rhs.denom - lhs.denom * rhs.num, rhs.denom * lhs.denom); } Frac multFrac(Frac lhs, Frac rhs) { return makeFrac(lhs.num * rhs.num, lhs.denom * rhs.denom); } bool equalFrac(Frac lhs, Frac rhs) { return (lhs.num == rhs.num) && (lhs.denom == rhs.denom); } bool lessFrac(Frac lhs, Frac rhs) { return (lhs.num * rhs.denom) < (rhs.num * lhs.denom); } void printFrac(Frac f) { char buffer[7]; int len; if (f.denom != 1) { snprintf(buffer, 7, , f.num, f.denom); } else { snprintf(buffer, 7, , f.num); } len = 7 - strlen(buffer); while (len-- > 0) { putc(' ', stdout); } printf(buffer); } Frac bernoulli(int n) { Frac a[16]; int j, m; if (n < 0) { a[0].num = 0; a[0].denom = 0; return a[0]; } for (m = 0; m <= n; ++m) { a[m] = makeFrac(1, m + 1); for (j = m; j >= 1; --j) { a[j - 1] = multFrac(subFrac(a[j - 1], a[j]), makeFrac(j, 1)); } } if (n != 1) { return a[0]; } return negateFrac(a[0]); } void faulhaber(int p) { Frac q, *coeffs; int j, sign; coeffs = malloc(sizeof(Frac)*(p + 1)); q = makeFrac(1, p + 1); sign = -1; for (j = 0; j <= p; ++j) { sign = -1 * sign; coeffs[p - j] = multFrac(multFrac(multFrac(q, makeFrac(sign, 1)), makeFrac(binomial(p + 1, j), 1)), bernoulli(j)); } for (j = 0; j <= p; ++j) { printFrac(coeffs[j]); } printf(); free(coeffs); } int main() { int i; for (i = 0; i < 10; ++i) { faulhaber(i); } return 0; }
855Faulhaber's triangle
5c
qz2xc
use strict; use warnings; use GD; my @fword = ( undef, 1, 0 ); sub fword { my $n = shift; return $fword[$n] if $n<3; return $fword[$n] //= fword($n-1).fword($n-2); } my $size = 3000; my $im = new GD::Image($size,$size); my $white = $im->colorAllocate(255,255,255); my $black = $im->colorAllocate(0,0,0); $im->transparent($white); $im->interlaced('true'); my @pos = (0,0); my @dir = (0,5); my @steps = split //, fword 23; my $i = 1; for( @steps ) { my @next = ( $pos[0]+$dir[0], $pos[1]+$dir[1] ); $im->line( @pos, @next, $black ); @dir = ( $dir[1], -$dir[0] ) if 0==$_ && 1==$i%2; @dir = ( -$dir[1], $dir[0] ) if 0==$_ && 0==$i%2; $i++; @pos = @next; } open my $out, ">", "fword.png" or die "Cannot open output file.\n"; binmode $out; print $out $im->png; close $out;
846Fibonacci word/fractal
2perl
zustb
null
845File size
11kotlin
8y10q
use strict; use warnings; use feature 'say'; use bigint try=>"GMP"; use ntheory qw<factor>; my @Fermats = map { 2**(2**$_) + 1 } 0..9; my $sub = 0; say 'First 10 Fermat numbers:'; printf "F%s =%s\n", $sub++, $_ for @Fermats; $sub = 0; say "\nFactors of first few Fermat numbers:"; for my $f (map { [factor($_)] } @Fermats[0..8]) { printf "Factors of F%s:%s\n", $sub++, @$f == 1 ? 'prime' : join ' ', @$f }
849Fermat numbers
2perl
tvefg
function leftShift(n,p) local r = n while p>0 do r = r * 2 p = p - 1 end return r end
848Feigenbaum constant calculation
1lua
2kdl3
def isExt(fileName, extensions): return True in map(fileName.lower().endswith, ( + e.lower() for e in extensions))
847File extension is in extensions list
3python
1i5pc
my $mtime = (stat($file))[9]; use File::stat qw(stat); my $mtime = stat($file)->mtime; utime(stat($file)->atime, time, $file);
844File modification time
2perl
hsujl
(defn fasta [pathname] (with-open [r (clojure.java.io/reader pathname)] (doseq [line (line-seq r)] (if (= (first line) \>) (print (format "%n%s: " (subs line 1))) (print line)))))
854FASTA format
6clojure
jqt7m
<?php $filename = 'input.txt'; $mtime = filemtime($filename); touch($filename, time(), fileatime($filename)); ?>
844File modification time
12php
zu8t1
from functools import wraps from turtle import * def memoize(obj): cache = obj.cache = {} @wraps(obj) def memoizer(*args, **kwargs): key = str(args) + str(kwargs) if key not in cache: cache[key] = obj(*args, **kwargs) return cache[key] return memoizer @memoize def fibonacci_word(n): assert n > 0 if n == 1: return if n == 2: return return fibonacci_word(n - 1) + fibonacci_word(n - 2) def draw_fractal(word, step): for i, c in enumerate(word, 1): forward(step) if c == : if i% 2 == 0: left(90) else: right(90) def main(): n = 25 step = 1 width = 1050 height = 1050 w = fibonacci_word(n) setup(width=width, height=height) speed(0) setheading(90) left(90) penup() forward(500) right(90) backward(500) pendown() tracer(10000) hideturtle() draw_fractal(w, step) getscreen().getcanvas().postscript(file=) exitonclick() if __name__ == '__main__': main()
846Fibonacci word/fractal
3python
350zc
(filter even? (range 0 100)) (vec (filter even? (vec (range 0 100))))
853Filter
6clojure
hs3jr
my $x = 0; recurse($x); sub recurse ($x) { print ++$x,"\n"; recurse($x); }
841Find limit of recursion
2perl
lhyc5
function GetFileSize( filename ) local fp = io.open( filename ) if fp == nil then return nil end local filesize = fp:seek( "end" ) fp:close() return filesize end
845File size
1lua
oma8h
def factors(x): factors = [] i = 2 s = int(x ** 0.5) while i < s: if x% i == 0: factors.append(i) x = int(x / i) s = int(x ** 0.5) i += 1 factors.append(x) return factors print() for i in range(10): fermat = 2 ** 2 ** i + 1 print(.format(chr(i + 0x2080) , fermat)) print() for i in range(10): fermat = 2 ** 2 ** i + 1 fac = factors(fermat) if len(fac) == 1: print(.format(chr(i + 0x2080))) else: print(.format(chr(i + 0x2080), fac))
849Fermat numbers
3python
zuwtt
use strict; use warnings; use Math::AnyNum 'sqr'; my $a1 = 1.0; my $a2 = 0.0; my $d1 = 3.2; print " i \n"; for my $i (2..13) { my $a = $a1 + ($a1 - $a2)/$d1; for (1..10) { my $x = 0; my $y = 0; for (1 .. 2**$i) { $y = 1 - 2 * $y * $x; $x = $a - sqr($x); } $a -= $x/$y; } $d1 = ($a1 - $a2) / ($a - $a1); ($a2, $a1) = ($a1, $a); printf "%2d%17.14f\n", $i, $d1; }
848Feigenbaum constant calculation
2perl
qz7x6
def is_ext(filename, extensions) if filename.respond_to?(:each) filename.each do |fn| is_ext(fn, extensions) end else fndc = filename.downcase extensions.each do |ext| bool = fndc.end_with?(?. + ext.downcase) puts % [filename, bool] if bool end end end
847File extension is in extensions list
14ruby
edgax
import os modtime = os.path.getmtime('filename') os.utime('path', (actime, mtime)) os.utime('path', (os.path.getatime('path'), mtime)) os.utime('path', None)
844File modification time
3python
k05hf
fibow <- function(n) { t2="0"; t1="01"; t=""; if(n<2) {n=2} for (i in 2:n) {t=paste0(t1,t2); t2=t1; t1=t} return(t) } pfibofractal <- function(n, w, h, d, clr) { dx=d; x=y=x2=y2=tx=dy=nr=0; if(n<2) {n=2} fw=fibow(n); nf=nchar(fw); pf = paste0("FiboFractR", n, ".png"); ttl=paste0("Fibonacci word/fractal, n=",n); cat(ttl,"nf=", nf, "pf=", pf,"\n"); plot(NA, xlim=c(0,w), ylim=c(-h,0), xlab="", ylab="", main=ttl) for (i in 1:nf) { fwi=substr(fw, i, i); x2=x+dx; y2=y+dy; segments(x, y, x2, y2, col=clr); x=x2; y=y2; if(fwi=="0") {tx=dx; nr=i%%2; if(nr==0) {dx=-dy;dy=tx} else {dx=dy;dy=-tx}} } dev.copy(png, filename=pf, width=w, height=h); dev.off(); graphics.off(); } pfibofractal(23, 1000, 1000, 1, "navy") pfibofractal(25, 2300, 1000, 1, "red")
846Fibonacci word/fractal
13r
dlwnt