2 |
3 | using namespace std;
4 |
5 | int main(int argc, char** argv) {
6 | long c = 1;
7 |
8 | while (1) {
9 | if ((++c % 10000000) == 0) {
10 | printf("%ld\n", c);
11 | }
12 | }
13 |
14 | return 0;
15 | }
16 |
--------------------------------------------------------------------------------
/cs/hellocoffee.html:
--------------------------------------------------------------------------------
1 |
3 |
4 |
14 |
--------------------------------------------------------------------------------
/emdr/.eslintrc:
--------------------------------------------------------------------------------
1 | {
2 | "root": true,
3 | "parser": "@typescript-eslint/parser",
4 | "plugins": [
5 | "@typescript-eslint",
6 | "prettier"
7 | ],
8 | "extends": [
9 | "eslint:recommended",
10 | "plugin:@typescript-eslint/eslint-recommended",
11 | "plugin:@typescript-eslint/recommended",
12 | "prettier"
13 | ],
14 | "rules": {
15 | "no-console": 1, // Means warning
16 | "prettier/prettier": 2 // Means error
17 | }
18 | }
--------------------------------------------------------------------------------
/emdr/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | dist
3 |
--------------------------------------------------------------------------------
/emdr/README.md:
--------------------------------------------------------------------------------
1 | # EMDR Remote
2 |
3 | ## Run
4 |
5 | ```
6 | npm run develop
7 | ```
8 |
--------------------------------------------------------------------------------
/emdr/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 | Remote EMDR
10 |
12 |
13 |
14 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/emdr/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "emdr",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1",
8 | "develop": "webpack-dev-server --mode development",
9 | "build": "webpack --mode production"
10 | },
11 | "keywords": [],
12 | "author": "",
13 | "license": "ISC",
14 | "devDependencies": {
15 | "@types/node": "^18.11.18",
16 | "@typescript-eslint/eslint-plugin": "^5.50.0",
17 | "@typescript-eslint/parser": "^5.50.0",
18 | "css-loader": "^6.7.3",
19 | "eslint": "^8.33.0",
20 | "html-webpack-plugin": "^5.5.0",
21 | "prettier": "^2.8.3",
22 | "style-loader": "^3.3.1",
23 | "ts-loader": "^9.4.2",
24 | "typescript": "^4.9.4",
25 | "webpack": "^5.75.0",
26 | "webpack-cli": "^5.0.1",
27 | "webpack-dev-server": "^4.11.1"
28 | },
29 | "dependencies": {
30 | "axios": "^1.3.2"
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/emdr/src/index.ts:
--------------------------------------------------------------------------------
1 | import Circle from './circle';
2 | import Bouncer from './bouncer';
3 |
4 | import './static/index.css'
5 |
6 | function main() {
7 | const circlebox = document.getElementById( 'circlebox' );
8 | const width = circlebox.getBoundingClientRect().width;
9 | const bouncer = new Bouncer(new Circle(300, 300, 30).createElement("circlebox"));
10 | bouncer.setBounds(100, width - 100);
11 |
12 | const startstopEl = document.getElementById("startstop") as HTMLButtonElement;
13 | startstopEl.addEventListener("click", function() {
14 | bouncer.toggle();
15 | startstopEl.innerHTML = bouncer.running ? "Stop" : "Start";
16 | });
17 |
18 | const speedEl = document.getElementById("speed") as HTMLInputElement;
19 | speedEl.addEventListener('change', function() {
20 | bouncer.setSpeed(Number(speedEl.value));
21 | });
22 | }
23 |
24 | main();
--------------------------------------------------------------------------------
/emdr/src/logger.ts:
--------------------------------------------------------------------------------
1 | let LOGLEVEL = 50;
2 |
3 | function log(level: number, ...args: string[]) {
4 | if (level <= LOGLEVEL) {
5 | // eslint-disable-next-line
6 | console.log(`[pitchy:${level}]`, ...args);
7 | }
8 | }
9 |
10 | function debug(...args: string[]) {
11 | log(50, ...args);
12 | }
13 |
14 | function info(...args: string[]) {
15 | log(30, ...args);
16 | }
17 |
18 | function warn(...args: string[]) {
19 | log(20, ...args);
20 | }
21 |
22 | function error(...args: string[]) {
23 | log(10, ...args);
24 | }
25 |
26 | function setLevel(level: number) {
27 | info('Setting log level to', level.toString());
28 | LOGLEVEL = level;
29 | }
30 |
31 | export {
32 | log, debug, info, warn, error, setLevel,
33 | };
--------------------------------------------------------------------------------
/emdr/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "noImplicitAny": true,
4 | "target": "ES5",
5 | "module": "ES2015"
6 | }
7 | }
--------------------------------------------------------------------------------
/emdr/webpack.config.js:
--------------------------------------------------------------------------------
1 | const HtmlWebpackPlugin = require("html-webpack-plugin");
2 | const path = require('path');
3 |
4 | module.exports = {
5 | entry: './src/index.ts',
6 | module: {
7 | rules: [
8 | { test: /\.ts?$/, use: 'ts-loader', exclude: /node_modules/, },
9 | { test: /\.css$/, use: ['style-loader', 'css-loader'] },
10 | ],
11 | },
12 | resolve: {
13 | extensions: ['.tsx', '.ts', '.js'],
14 | },
15 | output: {
16 | filename: 'bundle.js',
17 | path: path.resolve(__dirname, 'dist'),
18 | },
19 | devServer: {
20 | static: path.join(__dirname, "dist"),
21 | compress: true,
22 | port: 4000,
23 | },
24 | plugins: [
25 | new HtmlWebpackPlugin({
26 | title: 'Remote EMDR',
27 | template: 'index.html' })
28 | ],
29 | };
--------------------------------------------------------------------------------
/go/echo.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import ("os"
4 | "flag")
5 |
6 | var omitNewLine = flag.Bool("n", false, "Omit new line")
7 |
8 | const (Space = " "; Newline = "\n")
9 |
10 | func main() {
11 | flag.Parse()
12 |
13 | var s string = "";
14 |
15 | for i := 0; i < flag.NArg(); i++ {
16 | if i > 0 { s += Space }
17 |
18 | s += flag.Arg(i);
19 | }
20 |
21 | if !*omitNewLine { s += Newline }
22 |
23 | os.Stdout.WriteString(s)
24 | }
25 |
--------------------------------------------------------------------------------
/go/empty.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | // Bottom is a valueless type
6 | type Bottom struct{}
7 |
8 | func main() {
9 | set := make(map[string]Bottom)
10 | exists := Bottom{}
11 |
12 | set["foo"] = exists
13 | set["bar"] = exists
14 |
15 | fmt.Printf("%v+\n", set)
16 |
17 | for k, v := range set {
18 | fmt.Printf("%v = %v\n", k, v)
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/go/hello.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | func main() {
6 | fmt.Printf("hello, world\n");
7 | }
8 |
--------------------------------------------------------------------------------
/go/parity.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import "fmt"
4 |
5 | // Parity is a naive parity calculator
6 | func Parity(v int64) int64 {
7 | parity := int64(0)
8 |
9 | for v > 0 {
10 | parity ^= v & 1
11 | v >>= 1
12 | }
13 |
14 | return parity
15 | }
16 |
17 | func main() {
18 | fmt.Printf("1 << 0: %v\n", 1<<0)
19 | fmt.Printf("1 << 1: %v\n", 1<<1)
20 | fmt.Printf("1 << 2: %v\n", 1<<2)
21 | fmt.Printf("1 << 3: %v\n", 1<<3)
22 | fmt.Printf("parity of 1: %v\n", Parity(1))
23 | fmt.Printf("parity of 2: %v\n", Parity(2))
24 | fmt.Printf("parity of 3: %v\n", Parity(3))
25 | fmt.Printf("parity of 4: %v\n", Parity(4))
26 | }
27 |
--------------------------------------------------------------------------------
/go/wscript:
--------------------------------------------------------------------------------
1 | APPNAME = "gohello"
2 | VERSION = "1.0"
3 |
4 | top = "."
5 | out = "build"
6 |
7 | def configure(ctx):
8 | ctx.env.GOC = "6g"
9 | ctx.env.GOL = "6l"
10 |
11 | def build(ctx):
12 | sources = ["echo.go", "hello.go", "slices.go"]
13 |
14 | for file in sources:
15 | # Files with ".go" extensions are automatically compiled and linked
16 | ctx(source=file)
17 |
18 | # Remove .bin extension from file
19 | binary = file.replace(".go", "")
20 | ctx(rule="mv ${SRC} ${TGT}", source=(binary + ".bin"), target=binary)
21 |
22 | """
23 | Code to automatically compile and link files with ".go" as their extension.
24 | """
25 |
26 | from waflib import TaskGen
27 |
28 | TaskGen.declare_chain(
29 | name = "goc",
30 | rule = "${GOC} -o ${TGT} ${SRC}",
31 | ext_in = ".go",
32 | ext_out = ".6")
33 |
34 | TaskGen.declare_chain(
35 | name = "gol",
36 | rule = "${GOL} -o ${TGT} ${SRC}",
37 | ext_in = ".6",
38 | ext_out = ".bin",
39 | reentrant = False)
40 |
--------------------------------------------------------------------------------
/haskell/First.hs:
--------------------------------------------------------------------------------
1 | module Main where
2 | import System.Environment
3 | import Text.ParserCombinators.Parsec hiding (spaces)
4 |
5 | data Picture = Picture {pic_header::String, pic_body::[Int],
6 | pic_checksum::Int} deriving Show
7 |
8 | data LispVal = Atom String
9 | List [LispVal]
10 | DottedList [LispVal] LispVal
11 | Number Integer
12 | String String
13 | Bool Bool
14 |
15 | symbol :: Parser Char
16 | symbol = oneOf "!$#%&|*+-/:<=>?@^_-"
17 |
18 | spaces :: Parser ()
19 | spaces = skipMany1 space
20 |
21 | parseString :: Parser LispVal
22 | parseString = do char '"'
23 | x <- many (noneOf "\"")
24 | char '"'
25 | return $ String x
26 |
27 | readExpr :: String -> String
28 | readExpr input = case parse (spaces >> symbol) "lisp" input of
29 | Left err -> "No match: " ++ show err
30 | Right val -> "Found value"
31 |
32 | main :: IO ()
33 | main = do args <- getArgs
34 | putStrLn $ readExpr (args !! 0)
35 |
--------------------------------------------------------------------------------
/haskell/LineServerTest.hs:
--------------------------------------------------------------------------------
1 | import Control.Concurrent.MVar
2 | import System.IO
3 |
4 | import LineServer
5 |
6 | data State = State
7 | { payload :: String
8 | , counter :: MVar Int }
9 |
10 | myConnectHandler h = do
11 | putStrLn "New connection"
12 | hPutStrLn h "HELLO"
13 |
14 | myLineHandler state h line = do
15 | let ctrMVar = counter state
16 | ctr <- modifyMVar ctrMVar (\c -> return (c + 1, c))
17 | hPutStrLn h $ (payload state) ++ " [" ++ (show ctr) ++ "] : " ++ line
18 |
19 | myErrHandler errMsg = putStrLn $ "Connection closed: " ++ errMsg
20 |
21 | main = do
22 | ctr <- newMVar 0
23 |
24 | h <- LineServer.init $ Options
25 | { port = "10000"
26 | , connectHandler = myConnectHandler
27 | , lineHandler = (myLineHandler (State "hsterm" ctr))
28 | , errHandler = myErrHandler }
29 |
30 | start h
31 |
--------------------------------------------------------------------------------
/haskell/PCRESubTest.hs:
--------------------------------------------------------------------------------
1 | import PCRESub
2 |
3 | main = do
4 | let text = "me boo" =~$ ("(me) boo", "he \\1")
5 | print text
6 |
--------------------------------------------------------------------------------
/haskell/PNM.hs:
--------------------------------------------------------------------------------
1 | import qualified Data.ByteString.Lazy.Char8 as L8
2 | import qualified Data.ByteString.Lazy as L
3 | import Data.Char (isSpace)
4 |
5 | data Greymap = Greymap {
6 | greyWidth :: Int,
7 | greyHeight :: Int,
8 | greyMax :: Int,
9 | greyData :: L.ByteString
10 | } deriving (Eq)
11 |
12 | instance Show Greymap where
13 | show (Greymap w h m _) = "Greymap " ++ show w ++ "x" ++
14 | show h ++ " " ++ show m
15 |
16 | parseP5 :: L.ByteString -> Maybe (Greymap, L.ByteString)
17 |
18 | main = do
19 | putStrLn "Greymap 1.0"
20 | -- print $ Greymap 4 5 6 (L.ByteString "ABC")
21 |
22 |
--------------------------------------------------------------------------------
/haskell/Test.hs:
--------------------------------------------------------------------------------
1 | module Main
2 | where
3 |
4 | import IO
5 | import Random
6 |
7 | x = 5
8 | y = (6, "hello")
9 | z = x * fst y
10 |
11 | addthem x y = x + y
12 |
13 | run_this = do
14 | putStrLn ("A")
15 | putStrLn ("B")
16 |
17 | getNumbers = do
18 | putStrLn "enter a number: "
19 | word <- getLine
20 |
21 | if read word == 0
22 | then return []
23 | else do
24 | rest <- getNumbers
25 | return ((read word :: Int ): rest)
26 |
27 | showNumbers [] = return ()
28 | showNumbers (x:xs) = do
29 | putStrLn (show x)
30 | showNumbers xs
31 |
32 | my_min :: [a] -> Maybe a
33 | my_min [] = Nothing
34 | my_min (x:xs) = do
35 | min <- read my_min xs
36 | if min < x
37 | then Just min
38 | else Just x
39 |
40 |
41 | main = do
42 | numbers <- getNumbers
43 | showNumbers numbers
44 | putStrLn ("Minimum: ")
45 |
46 | min <- my_min numbers
47 | putStrLn (show min)
48 |
--------------------------------------------------------------------------------
/haskell/TokenBucketTest.hs:
--------------------------------------------------------------------------------
1 | -- Test harness for TokenBucket module.
2 | -- Mohit Cheppudira
3 |
4 | import TokenBucket
5 |
6 | main :: IO ()
7 | main = TokenBucket.test
8 |
--------------------------------------------------------------------------------
/haskell/avg.hs:
--------------------------------------------------------------------------------
1 | -- Custom average function calculates the length and sum in
2 | -- a single iteration.
3 |
4 | import System (getArgs)
5 |
6 | avg (x:xs) (sum,len) = avg xs ((x + sum), (len + 1))
7 | avg [] (sum,len) = sum / (fromIntegral len)
8 |
9 | average xs = avg xs (0,0)
10 |
11 | main = do
12 | args <- getArgs
13 |
14 | if length args > 0
15 | then putStrLn $ show $ average [1 .. (read $ args!!0)]
16 | else putStrLn "Usage: avg "
17 |
--------------------------------------------------------------------------------
/haskell/binary.hs:
--------------------------------------------------------------------------------
1 | import qualified Data.ByteString.Lazy.Char8 as L8
2 | import Control.Monad
3 | import Control.Applicative
4 | import Data.Char
5 |
6 | hello :: L8.ByteString
7 | hello = L8.pack "Hello World"
8 |
9 | ordify :: L8.ByteString -> [Int]
10 | ordify s = map ord (L8.unpack s)
11 |
12 | main = do
13 | L8.putStrLn hello
14 | print hello
15 | print $ ordify hello
16 |
17 | -- <$> = fmap
18 | ordify <$> (L8.readFile "binaryfile") >>= print
19 |
20 | -- same as above
21 | (L8.readFile "binaryfile") >>= (print . ordify)
22 |
--------------------------------------------------------------------------------
/haskell/binaryfile:
--------------------------------------------------------------------------------
1 | hello
2 |
--------------------------------------------------------------------------------
/haskell/chan.hs:
--------------------------------------------------------------------------------
1 | import Control.Concurrent
2 | import Control.Concurrent.Chan
3 | import Control.Monad
4 | import Ix
5 |
6 | chanExample = do
7 | -- Create channel
8 | chan <- newChan
9 |
10 | -- Spawn 10 threads and send messages to the channel.
11 | forM_ (range (1,10)) (\i -> forkIO $ writeChan chan (show i))
12 |
13 | -- Read messages from the channel.
14 | replicateM_ 10 (readChan chan >>= print)
15 |
16 | main = chanExample
17 |
--------------------------------------------------------------------------------
/haskell/concat.hs:
--------------------------------------------------------------------------------
1 | concatS:: String -> String -> String
2 | concatS s1 s2 = s1 ++ s2
3 |
4 | showI :: Int -> String
5 | showI i = show i
6 |
7 | -- g :: String -> Int -> String
8 | g n s = concatS (showI n) s
9 |
10 | -- foldright :: (String -> Int -> String) -> String -> [Int] -> String
11 | foldright h y [] = y
12 | foldright h y (x:xs) = h x (foldright h y xs)
13 |
14 | -- f :: [Int] -> String
15 | f l = foldright g "" l
16 |
17 | main = do
18 | print $ f [1,4,5]
19 |
--------------------------------------------------------------------------------
/haskell/debugging.hs:
--------------------------------------------------------------------------------
1 | import Debug.Trace
2 |
3 | -- A neat debugging trick. Use "trace" in a guard that always fails
4 | -- to log a message every time the function is evaluated.
5 |
6 | f :: Int -> Int
7 | f n | trace ("f was called: " ++ show n) False = undefined
8 | f 0 = 1
9 | f n = n * f (n - 1)
10 |
11 |
12 | main = do
13 | print $ f 7
14 |
--------------------------------------------------------------------------------
/haskell/elf.hs:
--------------------------------------------------------------------------------
1 | -- Usage: elf
2 |
3 | import qualified Data.ByteString.Lazy as L
4 | import System (getArgs)
5 |
6 | hasElfMagic :: L.ByteString -> Bool
7 | hasElfMagic content = L.take 4 content == elfMagic
8 | where elfMagic = L.pack [0x7f, 0x45, 0x4c, 0x46]
9 |
10 | isElfFile :: FilePath -> IO Bool
11 | isElfFile path = do
12 | content <- L.readFile path
13 | return $ hasElfMagic content
14 |
15 | main = do
16 | args <- getArgs
17 | isElf <- isElfFile $ args !! 0
18 | putStrLn $ if isElf then "ELF" else "NOT ELF"
19 |
--------------------------------------------------------------------------------
/haskell/euler1.hs:
--------------------------------------------------------------------------------
1 | -- Project Euler: Problem 1
2 | -- Author: Mohit Muthanna Cheppudira
3 | --
4 | -- If we list all the natural numbers below 10 that are multiples of 3 or 5,
5 | -- we get 3, 5, 6 and 9. The sum of these multiples is 23.
6 | --
7 | -- Find the sum of all the multiples of 3 or 5 below 1000.
8 |
9 | import System (getArgs)
10 |
11 | sum35 :: Int -> Int
12 | sum35 n = sum $ filter multiple35 $ [1..n-1]
13 | where multiple35 a = any ((== 0) . (a `mod`)) [3, 5]
14 |
15 | main :: IO ()
16 | main = do
17 | a <- getArgs
18 | print $ sum35 $ if length a == 0 then 1000 else read $ a !! 0
19 |
--------------------------------------------------------------------------------
/haskell/euler10.hs:
--------------------------------------------------------------------------------
1 | -- Project Euler: Problem 10
2 | -- Author: Mohit Muthanna Cheppudira
3 | --
4 | -- Calculate the sum of all the primes below two million.
5 |
6 | import System (getArgs)
7 |
8 | -- Memoized prime number generator.
9 | primes :: Integral a => [a]
10 | primes = 3 : 5 : filter (not . hasFactor) [7,9..]
11 | where hasFactor n = any (divides n) $ takeWhile (<= lowestFactor n) primes
12 | divides n m = n `mod` m == 0
13 | lowestFactor = ceiling . sqrt . fromIntegral
14 |
15 | euler10 :: Int -> Int
16 | euler10 limit = sum $ takeWhile (< limit) (primes :: [Int])
17 |
18 | main :: IO ()
19 | main = do
20 | a <- getArgs
21 | print $ euler10 $ defaultArg a 2000000
22 | where defaultArg a b = if length a == 0 then b else read $ a !! 0
23 |
--------------------------------------------------------------------------------
/haskell/euler2.hs:
--------------------------------------------------------------------------------
1 | -- Project Euler: Problem 2
2 | -- Author: Mohit Muthanna Cheppudira
3 | --
4 | -- Each new term in the Fibonacci sequence is generated by adding the previous
5 | -- two terms. By starting with 1 and 2, the first 10 terms will be:
6 | --
7 | -- 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
8 | --
9 | -- Find the sum of all the even-valued terms in the sequence which do not
10 | -- exceed four million.
11 |
12 | import System (getArgs)
13 |
14 | -- Simple memoized Fibonacci sequence
15 | fibs :: [Integer]
16 | fibs = map genFib [0..]
17 | where
18 | genFib 0 = 0
19 | genFib 1 = 1
20 | genFib 2 = 2
21 | genFib x = (fibs !! (x - 1)) + (fibs !! (x - 2))
22 |
23 | -- Solving Euler 2 for arbitrary limit
24 | euler2 :: Integer -> Integer
25 | euler2 limit = sum $ filter (not . odd) (takeWhile ( [Integer]
19 | primeFactors n = takeUntil allFactorsFound [] $ filter isFactor primes
20 | where takeUntil d acc (x:xs) =
21 | if d (x:acc) then (x:acc) else takeUntil d (x:acc) xs
22 | allFactorsFound acc = product acc == n
23 | isFactor m = n `mod` m == 0
24 |
25 | main :: IO ()
26 | main = do
27 | a <- getArgs
28 | print $ maximum $ primeFactors $ defaultArg a 600851475143
29 | where defaultArg a b = if length a == 0 then b else read $ a !! 0
30 |
--------------------------------------------------------------------------------
/haskell/euler7.hs:
--------------------------------------------------------------------------------
1 | -- Project Euler: Problem 7
2 | -- Author: Mohit Muthanna Cheppudira
3 | --
4 | -- Find the 10001st Prime
5 |
6 | import System (getArgs)
7 |
8 | -- Memoized prime number generator.
9 | primes :: [Int]
10 | primes = 2 : 3 : 5 : filter (not . hasFactor) [7..]
11 | where hasFactor n = any (divides n) $ takeWhile (<= lowestFactor n) primes
12 | divides n m = n `mod` m == 0
13 | lowestFactor = ceiling . sqrt . fromIntegral
14 |
15 | main :: IO ()
16 | main = do
17 | a <- getArgs
18 | print $ primes !! ((defaultArg a 10001) - 1)
19 | where defaultArg a b = if length a == 0 then b else read $ a !! 0
20 |
--------------------------------------------------------------------------------
/haskell/factrec.hs:
--------------------------------------------------------------------------------
1 | {-# LANGUAGE FlexibleInstances #-}
2 |
3 | y f = f $ y ( f )
4 |
5 | factRec g x = case x of
6 | 0 -> 1
7 | _ -> x * (g (x - 1))
8 |
9 | fact = y factRec
10 |
11 | fibRec g x = case x of
12 | 0 -> 0
13 | 1 -> 1
14 | _ -> (g (x - 1) + g (x - 2))
15 |
16 | fib = y fibRec
17 |
18 | reduceRec g f l = case l of
19 | [] -> undefined
20 | [x] -> x
21 | (x : xs) -> f x (g f xs)
22 |
23 | reduce = y reduceRec
24 |
--------------------------------------------------------------------------------
/haskell/file.hs:
--------------------------------------------------------------------------------
1 | module Main
2 | where
3 |
4 | import IO
5 |
6 | file = "file.txt"
7 |
8 | process :: String -> Int
9 | process contents =
10 | let x = read $ take 1 contents in
11 | x + 1
12 |
13 | main = do
14 | bracket (openFile file ReadMode) hClose
15 | (\h -> do contents <- hGetContents h
16 | putStrLn $ show $ process contents)
17 | putStrLn "All done!"
18 |
--------------------------------------------------------------------------------
/haskell/file.txt:
--------------------------------------------------------------------------------
1 | 1
2 | 2
3 | 3
4 | 4
5 |
--------------------------------------------------------------------------------
/haskell/fold.hs:
--------------------------------------------------------------------------------
1 | main = do
2 | -- This won't compile.
3 | -- print $ foldl (:) [] [1..10] -- Does not compile, obviously!
4 | print $ foldr (:) [] [1..10]
5 |
6 | -- These work
7 | print $ foldl (+) 0 [1..10]
8 | print $ foldr (+) 0 [1..10]
9 |
--------------------------------------------------------------------------------
/haskell/hello.hs:
--------------------------------------------------------------------------------
1 | -- Haskell is very very fast, so if you're calling this, you
2 | -- should be throttling.
3 | shouldThrottle = True
4 |
5 | main = do
6 | putStrLn "Hello World!"
7 |
--------------------------------------------------------------------------------
/haskell/hexdump.hs:
--------------------------------------------------------------------------------
1 | -- Usage: hexdump
2 | -- Author: Mohit Cheppudira
3 |
4 | import Control.Monad (when)
5 | import Data.Char
6 | import Data.List
7 | import Numeric
8 | import qualified Data.ByteString.Lazy as L
9 | import System.Exit
10 | import System (getArgs)
11 | import Text.Printf
12 |
13 | bytesPerLine = 16
14 |
15 | toHex c = showIntAtBase 16 intToDigit c ""
16 | toHexList = (map $ printf "%02s" . toHex) . L.unpack
17 |
18 | fileToHex path = do
19 | content <- L.readFile path
20 | return $ toHexList content
21 |
22 | formatList 0 _ = error "x < 1"
23 | formatList x [] = []
24 | formatList x l = h : formatList x t
25 | where (h, t) = splitAt x l
26 |
27 | showWithAddress [] _ = []
28 | showWithAddress (x:xs) a = prettify : showWithAddress xs (a + bytesPerLine)
29 | where prettify = (toHex a) ++ " " ++ (intercalate " " x)
30 |
31 | showHexFile file = do
32 | hexData <- fileToHex $ file
33 | mapM putStrLn $ showWithAddress (formatList bytesPerLine hexData) 0
34 |
35 | main = do
36 | args <- getArgs
37 |
38 | when (length args /= 1) $ do
39 | putStrLn "Syntax: hexdump "
40 | exitFailure
41 |
42 | showHexFile $ args !! 0
43 |
--------------------------------------------------------------------------------
/haskell/http.hs:
--------------------------------------------------------------------------------
1 | import Control.Monad
2 | import Control.Applicative
3 | import Data.Maybe
4 | import Network.HTTP
5 | import Network.URI
6 | import System (getArgs)
7 |
8 | downloadURL :: String -> IO (Either String String)
9 | downloadURL url =
10 | do resp <- simpleHTTP request
11 | case resp of
12 | Left x -> return $ Left $ "Error: " ++ show x
13 | Right r ->
14 | case rspCode r of
15 | (2, _, _) -> return $ Right (rspBody r)
16 | _ -> return $ Left $ "Error: " ++ show r
17 | where request = Request { rqURI = uri,
18 | rqMethod = GET,
19 | rqHeaders = [],
20 | rqBody = "" }
21 | uri = fromJust $ parseURI url
22 |
23 | wget :: String -> IO String
24 | wget url = do
25 | body <- downloadURL url
26 | case body of
27 | Left x -> return x
28 | Right r -> return r
29 |
30 | main :: IO ()
31 | main = do
32 | args <- getArgs
33 | if length args == 0
34 | then putStrLn "Usage: http.hs url"
35 | else putStrLn =<< (wget $ args !! 0)
36 |
37 |
--------------------------------------------------------------------------------
/haskell/interact.hs:
--------------------------------------------------------------------------------
1 | import System.Environment (getArgs)
2 | import Data.Char
3 |
4 | upperify = map toUpper
5 |
6 | interactWith function inputFile outputFile = do
7 | input <- readFile inputFile
8 | writeFile outputFile (function input)
9 |
10 | main = mainWith myFunction
11 | where mainWith function = do
12 | args <- getArgs
13 | case args of
14 | [input, output] -> interactWith function input output
15 | _ -> putStrLn "error: two arguments needed"
16 |
17 | myFunction = upperify
18 |
--------------------------------------------------------------------------------
/haskell/io.hs:
--------------------------------------------------------------------------------
1 | -- times :: Integer -> a -> m ()
2 | times 0 f = return ()
3 | times x f = do
4 | f
5 | times (x - 1) f
6 |
7 | -- This works because the type of main is IO t
8 | main = do
9 | putStrLn "How many more times?"
10 | inpStr <- getLine
11 | times (read inpStr) (putStrLn "Hello")
12 |
13 |
--------------------------------------------------------------------------------
/haskell/join.hs:
--------------------------------------------------------------------------------
1 | join :: String -> [String] -> String
2 | join s (x : []) = x
3 | join s (x : xs) = x ++ s ++ (join s xs)
4 | join s [] = []
5 |
6 |
7 | main = do
8 | print $ join ", " ["a", "b", "c"]
9 |
--------------------------------------------------------------------------------
/haskell/list.hs:
--------------------------------------------------------------------------------
1 | remove_second xs =
2 | head xs : tail (tail xs)
3 |
4 | main = do
5 | print $ remove_second [1, 2, 3, 4, 5, 6]
6 |
--------------------------------------------------------------------------------
/haskell/logger.hs:
--------------------------------------------------------------------------------
1 | -- Build a logger monad, and use it in an operation
2 |
3 | type Log = [String]
4 |
5 | newtype Logger a = Logger { execLogger :: (a, Log) }
6 |
7 | -- Here runLogger is aliased to execLogger. This works because
8 | -- execLogger is a function that takes a Logger and returns the
9 | -- associated data element: (a, Log).
10 | runLogger :: Logger a -> (a, Log)
11 | runLogger = execLogger
12 |
13 | -- Return nothing, just log the string.
14 | record s = Logger ((), [s])
15 |
16 | instance Monad Logger where
17 | -- Return a, log nothing
18 | return a = Logger (a, [])
19 |
20 | -- The magic happens here. Execute m then k, and concatenate
21 | -- the associated log message array.
22 | m >>= k = let (a, w) = execLogger m
23 | n = k a
24 | (b, x) = execLogger n
25 | in Logger (b, w ++ x)
26 |
27 |
28 | main = do print $ runLogger $
29 | do record "Hello World!"
30 | return 3.1337
31 |
--------------------------------------------------------------------------------
/haskell/max.hs:
--------------------------------------------------------------------------------
1 | module Main
2 | where
3 |
4 | import System
5 |
6 | type Person = String
7 | type Book = String
8 |
9 | type Database = [ (Person, Book) ]
10 |
11 | exampleBase :: Database
12 | exampleBase = [ ("Mohit", "Life of Pi"), ("Anna", "Asterix"),
13 | ("Jon", "Slaves to the Grind"), ("Mohit", "Machine Learning")]
14 |
15 | borrow :: Database -> Person -> Book -> Database
16 | borrow d p b = (p, b):d
17 |
18 | maxarr :: [Int] -> Int
19 | maxarr (x:xs) | xs == [] = x
20 | | otherwise = max x (maxarr xs)
21 | maxarr [] = 0
22 |
23 | minarr :: [Int] -> Int
24 | minarr (x:xs)
25 | | xs == [] = x
26 | | otherwise = min x (minarr xs)
27 | minarr [] = 0
28 |
29 | sumarr :: [Int] -> Int
30 | sumarr [] = 0
31 | sumarr (x:xs) = x + (sumarr xs)
32 |
33 | main = do
34 | args <- getArgs
35 | let arr = map read args
36 | print arr
37 | putStrLn $ "Maximum: " ++ (show $ maxarr arr)
38 | putStrLn $ "Minimum: " ++ (show $ minarr arr)
39 | putStrLn $ "Sum: " ++ (show $ sumarr arr)
40 | print exampleBase
41 | print $ borrow exampleBase "George" "The World is Flat"
42 |
--------------------------------------------------------------------------------
/haskell/maybe.hs:
--------------------------------------------------------------------------------
1 | import Data.Maybe
2 |
3 | main = do
4 | print $ Just "just"
5 | print $ fromMaybe "Nothing" $ Just "just"
6 |
--------------------------------------------------------------------------------
/haskell/min.hs:
--------------------------------------------------------------------------------
1 | mymin :: (Ord a) => a -> a -> a
2 | mymin a b = if a < b then a
3 | else b
4 |
5 | mymax :: (Ord a) => a -> a -> a
6 | mymax a b = if a > b then a
7 | else b
8 |
9 | minarr :: (Ord a) => [a] -> Maybe a
10 | minarr [] = Nothing
11 | minarr xs = Just $ helper xs
12 | where helper (x : []) = x
13 | helper (x : xs) = mymin x (helper xs)
14 |
15 | minarr2 :: (Ord a) => [a] -> Maybe a
16 | minarr2 [] = Nothing
17 | minarr2 (x : xs) = Just $ foldr mymin x xs
18 |
19 | fromMaybe :: a -> Maybe a -> a
20 | fromMaybe defval Nothing = defval
21 | fromMaybe defval (Just a) = a
22 |
23 | main = do
24 | print $ mymin 4 5
25 | print $ mymax 4 5
26 | print $ fromMaybe (-1) (minarr [12, 4, 5, 76, 3, 4, 4, 8, 43])
27 | print $ fromMaybe (-1) (minarr2 [12, 4, 5, 76, 3, 4, 4, 8, 43])
28 | print $ fromMaybe (-1) (minarr2 [])
29 |
--------------------------------------------------------------------------------
/haskell/mvar.hs:
--------------------------------------------------------------------------------
1 | import Control.Concurrent
2 | import Control.Monad
3 | import Ix (range)
4 |
5 | communicate :: Int -> IO ()
6 | communicate n = do
7 | m <- newEmptyMVar
8 |
9 | thread_list <- forM (range (1, n)) $ \i -> forkIO $ putMVar m i
10 |
11 | putStrLn $ "Started threads: " ++ show thread_list
12 |
13 | replicateM_ n $ do
14 | v <- takeMVar m
15 | putStrLn $ "Got: " ++ show v
16 |
17 | main :: IO ()
18 | main = communicate 10
19 |
--------------------------------------------------------------------------------
/haskell/pardata.hs:
--------------------------------------------------------------------------------
1 | {-# LANGUAGE PArr #-}
2 |
3 | -- Testing Parallel Arrays
4 | -- $ ghc --make -threaded -fdph-par -fforce-recomp pardata.hs
5 | -- $ ./pardata +RTS -N2
6 |
7 | import Data.Array.Parallel.Prelude
8 | import qualified Data.Array.Parallel.Prelude.Double as D
9 |
10 | sumSq :: [: Double :] -> Double
11 | sumSq a = D.sumP (mapP (\x -> x * x) a)
12 |
13 | main :: IO ()
14 | main = do
15 | let sum = sumSq [: 4, 5, 6, 3.2, 5.3, 45.2 :]
16 | putStrLn $ show sum
17 |
--------------------------------------------------------------------------------
/haskell/picture.hs:
--------------------------------------------------------------------------------
1 | module Main where
2 |
3 | import Data.List
4 |
5 | type PictureHeader = String
6 | type PictureBody = [Int]
7 | type Checksum = Int
8 |
9 | data Picture = Picture {
10 | pic_header :: PictureHeader,
11 | pic_body :: PictureBody,
12 | pic_checksum :: Checksum
13 | } deriving Show
14 |
15 | validPic p =
16 | case pic_header p of
17 | "" -> Nothing
18 | _ -> Just "Valid"
19 |
20 | fromMaybe defval wrapped =
21 | case wrapped of
22 | Nothing -> defval
23 | Just value -> value
24 |
25 | main = do
26 | let p = Picture "Hello" [1,2,3] 5
27 | let q = Picture "" [1, 2, 3] 6
28 |
29 | print p
30 | print q
31 |
32 | putStrLn $ "Picture header: " ++ pic_header (p)
33 |
34 | putStrLn $ "Valid: " ++ (fromMaybe "Invalid" $ validPic (p))
35 | putStrLn $ "Valid: " ++ (fromMaybe "Invalid" $ validPic (q))
36 |
--------------------------------------------------------------------------------
/haskell/powerset.hs:
--------------------------------------------------------------------------------
1 | powerSet' = foldr (\x -> concatMap (\xs -> [x:xs,xs])) [[]]
2 |
3 | main = do
4 | print $ powerSet' ['m', 'o', 'h', 'i', 't']
5 |
--------------------------------------------------------------------------------
/haskell/quicksort.hs:
--------------------------------------------------------------------------------
1 | -- quick and dirty super simple quicksort functions
2 |
3 | sort (x:xs) = lesser ++ x:greater
4 | where lesser = sort $ filter (x) xs
6 | sort _ = []
7 |
8 | sort1 (x:xs) = (pivot (x)
9 | where pivot f = sort1 $ filter f xs
10 | sort1 _ = []
11 |
12 | sort2 (x:xs) = sort2 [y | y <-xs, y < x] ++ x : sort2 [y | y <-xs, y > x]
13 | sort2 _ = []
14 |
15 | sort3 (x:xs) = (sort3 $ filter (x) xs)
16 | sort3 _ = []
17 |
18 | myarray = [3,4,6,2,4,1,39,4,48,3,43,23,18,04]
19 |
20 | main = do print $ sort myarray
21 | print $ sort1 myarray
22 | print $ sort2 myarray
23 | print $ sort3 myarray
24 |
--------------------------------------------------------------------------------
/haskell/random.hs:
--------------------------------------------------------------------------------
1 | module Main
2 | where
3 |
4 | import IO
5 | import Random
6 |
7 | doGuessing num = do
8 | putStrLn "Your guess?"
9 | guess <- getLine
10 | let guessNum = read guess
11 | if guessNum < num
12 | then do putStrLn "Too low!"
13 | doGuessing num
14 | else if guessNum > num
15 | then do putStrLn "Too high"
16 | doGuessing num
17 | else do putStrLn "Correct!"
18 |
19 | main = do
20 | hSetBuffering stdin LineBuffering
21 | num <- randomRIO(1::Int, 100)
22 | putStrLn "I'm thinking of a number between 1 and 100"
23 | doGuessing num
24 |
--------------------------------------------------------------------------------
/haskell/readert.hs:
--------------------------------------------------------------------------------
1 | import Control.Monad.Reader
2 |
3 | doThis :: ReaderT String IO ()
4 | doThis = do
5 | val <- ask
6 | liftIO . putStrLn $ val
7 |
8 | main = do
9 | runReaderT doThis "Boo"
10 |
--------------------------------------------------------------------------------
/haskell/readline.hs:
--------------------------------------------------------------------------------
1 | -- Test the readline library, with history recall.
2 |
3 | module Main (main) where
4 |
5 | import IO
6 | import Maybe
7 | import System.Console.Readline
8 |
9 | getline :: IO String
10 | getline = do
11 | line <- readline "> "
12 | let parsed_line = fromJust line
13 | addHistory parsed_line
14 | return $ parsed_line
15 |
16 | main :: IO ()
17 | main = do
18 | line <- getline
19 | if line == "q"
20 | then return ()
21 | else main
22 |
--------------------------------------------------------------------------------
/haskell/regsub.hs:
--------------------------------------------------------------------------------
1 | import Text.Regex
2 | import Text.Regex.PCRE
3 |
4 | main = print $ subRegex (mkRegex "(me) boo") "me boo" "he \\1"
5 |
--------------------------------------------------------------------------------
/haskell/renamer.hs:
--------------------------------------------------------------------------------
1 | -- Requires PCRE
2 | --
3 | -- cabal install regex-pcre
4 |
5 | import Control.Applicative
6 | import Control.Monad
7 | import Data.List
8 | import System
9 | import System.Posix.Directory
10 | import System.Posix.Files
11 | import Text.Regex.PCRE
12 |
13 | ls :: String -> IO ExitCode
14 | ls params = system $ "ls " ++ params
15 |
16 | getDirEntries :: FilePath -> IO [FilePath]
17 | getDirEntries dir = openDirStream dir >>= start
18 | where start s = readDirStream s >>= rest s
19 | rest s "" = return []
20 | rest s entry = liftM (entry:) (start s)
21 |
22 | main :: IO ()
23 | main = do
24 | if length args < 2
25 | then putStrLn "Usage: renamer dir match"
26 | else do
27 | files <- getDirEntries $ args !! 0
28 | let matches = filter (=~ (args !! 1)) files
29 | print matches
30 |
--------------------------------------------------------------------------------
/haskell/splitlines.hs:
--------------------------------------------------------------------------------
1 | -- Cross platfrom line-splitting.
2 | -- Better than 'lines'
3 |
4 | splitLines [] = []
5 | splitLines cs =
6 | let (pre, suf) = break isNewLine cs
7 | in pre : case suf of
8 | ('\r':'\n':rest) -> splitLines rest
9 | ('\r':rest) -> splitLines rest
10 | ('\n':rest) -> splitLines rest
11 | _ -> []
12 |
13 | isNewLine c = c == '\r' || c == '\n'
14 |
15 | main = do
16 | print $ splitLines "Hello\nHow\rAre\r\nYou?"
17 |
18 |
--------------------------------------------------------------------------------
/haskell/stmonad.hs:
--------------------------------------------------------------------------------
1 | import Control.Monad.ST.Lazy
2 | import Data.STRef.Lazy
3 |
4 | for (a, n) f = if a > n then return ()
5 | else do
6 | f a
7 | for (a + 1, n) f
8 |
9 | showA n = runST $ do
10 | r <- newSTRef 0
11 | for (1, n) (\x -> do
12 | val <- readSTRef r
13 | writeSTRef r (val + 1)
14 | )
15 | readSTRef r
16 |
17 | main = do print $ showA 5
18 |
--------------------------------------------------------------------------------
/haskell/suffixes.hs:
--------------------------------------------------------------------------------
1 | import Data.List
2 |
3 | suffixes (x:xs) = (x:xs) : suffixes xs
4 | suffixes [] = []
5 |
6 | suffixes2 = init . tails
7 |
8 | suffixes3 xs@(x:xs') = xs : suffixes xs'
9 | suffixes3 _ = []
10 |
11 | main = do
12 | print $ suffixes "foobar"
13 | print $ suffixes2 "foobar"
14 | print $ suffixes3 "foobar"
15 |
--------------------------------------------------------------------------------
/haskell/t1.hs:
--------------------------------------------------------------------------------
1 | import Data.Char
2 |
3 | data Tree a = TreeNode (Tree a) (Tree a) a | LeafNode a
4 | deriving (Show)
5 |
6 | process = map toUpper
7 |
8 | tree = TreeNode (LeafNode "a") (LeafNode "b") "r"
9 |
10 | main = do
11 | putStrLn "What's your name, bozo?"
12 | s <- getLine
13 | putStrLn $ "Hello " ++ (process s) ++ "!"
14 | putStrLn $ show tree
15 |
--------------------------------------------------------------------------------
/haskell/typeclass.hs:
--------------------------------------------------------------------------------
1 | {-# LANGUAGE TypeSynonymInstances #-}
2 |
3 | data JValue = JBool Bool |
4 | JString String
5 | deriving (Show)
6 |
7 | class JSON a where
8 | toJValue :: a -> JValue
9 | fromJValue :: JValue -> Maybe a
10 |
11 | instance JSON JValue where
12 | toJValue = id
13 | fromJValue = Just
14 |
15 | instance JSON Bool where
16 | toJValue = JBool
17 | fromJValue (JBool b) = Just b
18 | fromJValue _ = Nothing
19 |
20 | fromMaybe defval Nothing = defval
21 | fromMaybe defval (Just v) = v
22 |
23 | main = do
24 | print $ fromMaybe "Nothing" (Just "A")
25 | print $ fromMaybe "Nothing" Nothing
26 | print $ toJValue True
27 | print $ ((fromJValue (toJValue False)) :: Maybe Bool)
28 |
--------------------------------------------------------------------------------
/haskell/udpserver.hs:
--------------------------------------------------------------------------------
1 | import Data.Bits
2 | import Network.Socket
3 | import Network.BSD
4 | import Data.List
5 |
6 | type HandlerFunc = SockAddr -> String -> IO ()
7 |
8 | getAddress port = do
9 | addressinfos <- addresses
10 | return $ head addressinfos
11 | where addresses = getAddrInfo
12 | (Just (defaultHints {addrFlags = [AI_PASSIVE]}))
13 | Nothing (Just port)
14 |
15 | udpServer :: String -> HandlerFunc -> IO ()
16 | udpServer port handlerfunc = withSocketsDo $
17 | do
18 | serveraddr <- getAddress port
19 | sock <- socket (addrFamily serveraddr) Datagram defaultProtocol
20 | bindSocket sock (addrAddress serveraddr)
21 | procMessages sock
22 | where procMessages sock =
23 | do
24 | (msg, _, addr) <- recvFrom sock 1024
25 | handlerfunc addr msg
26 | procMessages sock
27 |
28 |
29 | plainHandler :: HandlerFunc
30 | plainHandler addr msg =
31 | putStrLn $ "From " ++ show addr ++ ": " ++ msg
32 |
33 | main = do
34 | let portNum = "8888"
35 | serveraddr <- getAddress portNum
36 | putStrLn $ "Listening on " ++ (show $ addrAddress serveraddr) ++ "/udp"
37 | udpServer portNum plainHandler
38 |
--------------------------------------------------------------------------------
/haskell/unlines.hs:
--------------------------------------------------------------------------------
1 | import System.Environment (getArgs)
2 |
3 | splitLines [] = []
4 | splitLines cs =
5 | let (pre, suf) = break isNewLine cs
6 | in pre : case suf of
7 | ('\r':'\n':rest) -> splitLines rest
8 | ('\r':rest) -> splitLines rest
9 | ('\n':rest) -> splitLines rest
10 | _ -> []
11 |
12 | isNewLine c = c == '\r' || c == '\n'
13 |
14 | interactWith function inputFile outputFile = do
15 | input <- readFile inputFile
16 | writeFile outputFile (function input)
17 |
18 | fixLines input = unlines (splitLines input)
19 |
20 | main = mainWith myFunction
21 | where mainWith function = do
22 | args <- getArgs
23 | case args of
24 | [input, output] -> interactWith function input output
25 | _ -> putStrLn "error: two arguments needed"
26 |
27 | myFunction = fixLines
28 |
--------------------------------------------------------------------------------
/haskell/unwrapio.hs:
--------------------------------------------------------------------------------
1 | -- You can't unwrap an IO because it's a data constructor that's not
2 | -- in scope.
3 |
4 | somestring = return "ABC"
5 |
6 | unwrap (IO a) = a
7 |
8 | stuff = unwrap somestring
9 |
10 | main = do
11 | putStrLn stuff
12 |
--------------------------------------------------------------------------------
/haskell/vector.hs:
--------------------------------------------------------------------------------
1 | data Vector a = Vector a a a
2 | deriving (Show)
3 |
4 | sumof :: (Num t) => Vector t -> t
5 | sumof (Vector a b c) = a + b + c
6 |
7 | main :: IO ()
8 | main = do
9 | print $ sumof (Vector 1 2 3)
10 | print $ "Is all"
11 |
--------------------------------------------------------------------------------
/haskell/wc.hs:
--------------------------------------------------------------------------------
1 | main = interact wordCount
2 | where wordCount input = show (length (lines input)) ++ "\n"
3 |
--------------------------------------------------------------------------------
/haskell/xmlrep.hs:
--------------------------------------------------------------------------------
1 | data H_XML = Tag { name::String, children::[H_XML]}
2 | | Value { name::String, value::String }
3 |
4 | instance Show H_XML where
5 | show x = xml_show x
6 |
7 | instance Read H_XML where
8 | read x = xml_read x
9 |
10 | class XML_Rep a where
11 | toXML :: a -> H_XML
12 | fromXML :: H_XML -> a
13 |
14 | xml_show x = "String"
15 | xml_read x = Tag "Nothing" [Value "Int" "One"]
16 |
17 | main = do
18 | print $ show $ read "A"
19 |
--------------------------------------------------------------------------------
/images/cleanup.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | INPUT=$1
4 | OUTPUT=$2
5 | TMP=/tmp/snfsoudnf
6 |
7 | if [ "$2" == "" ]; then
8 | echo "Usage: $0 input output"
9 | exit
10 | fi
11 |
12 | echo Blurring...
13 | convert $INPUT -threshold '85%' -gaussian-blur 20 -quality 20 ${TMP}1.jpg
14 |
15 | echo Tracing...
16 | autotrace -despeckle-level 9 -despeckle-tightness 0.6 \
17 | -error-threshold 1 -output-format pdf -filter-iterations 8 \
18 | -report-progress ${TMP}1.jpg >${TMP}2.pdf
19 |
20 | echo Downsampling...
21 | convert ${TMP}2.pdf -quality 20 $OUTPUT
22 |
--------------------------------------------------------------------------------
/java/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/0xfe/experiments/7f957a1cb3b0b041079f30bf1527cfb0498ee527/java/.DS_Store
--------------------------------------------------------------------------------
/java/AdviceGuy.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.net.*;
3 |
4 | public class AdviceGuy {
5 | String[] adviceList = {
6 | "Take smaller bites",
7 | "One word: inappropriate",
8 | "Just for today, be honest. Lie tomorrow",
9 | "You might want to rethink that haircut"
10 | };
11 |
12 | boolean running = true;
13 |
14 | public void go() {
15 | try {
16 | ServerSocket s = new ServerSocket(4242);
17 |
18 | while (running) {
19 | Socket sock = s.accept();
20 | new Thread(new AdvisorThread(sock)).start();
21 | }
22 | } catch (IOException ex) {
23 | ex.printStackTrace();
24 | }
25 | }
26 |
27 | public class AdvisorThread implements Runnable {
28 | Socket sock;
29 |
30 | public AdvisorThread(Socket s) {
31 | sock = s;
32 | }
33 |
34 | public void run() {
35 | try {
36 | PrintWriter writer = new PrintWriter(sock.getOutputStream());
37 | writer.println(adviceList[(int) (Math.random() * adviceList.length)]);
38 | writer.close();
39 | } catch (IOException ex) {
40 | ex.printStackTrace();
41 | }
42 | }
43 | }
44 |
45 |
46 | public static void main(String[] args) {
47 | new AdviceGuy().go();
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/java/Dog.java:
--------------------------------------------------------------------------------
1 | class Dog {
2 | int vigour;
3 | String name;
4 |
5 | public Dog() {
6 | name = "Nobody";
7 | vigour = 1;
8 | }
9 |
10 | public void bark() {
11 | String bark = "";
12 | int x = 0;
13 |
14 | for (x = 0; x < vigour; x++) {
15 | bark += "Ruff!! ";
16 | }
17 |
18 | System.out.println(name + ": " + bark);
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/java/DogTester.java:
--------------------------------------------------------------------------------
1 | public class DogTester {
2 | public static void main(String[] args) {
3 | Dog dog = new Dog();
4 | dog.vigour = 4;
5 | dog.name = "Rufus";
6 |
7 | dog.bark();
8 |
9 | Dog nodog = new Dog();
10 | nodog.bark();
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/java/EasyChatServer.java:
--------------------------------------------------------------------------------
1 | import java.io.*;
2 | import java.net.*;
3 |
4 |
--------------------------------------------------------------------------------
/java/HelloWorld.java:
--------------------------------------------------------------------------------
1 | class HelloWorld {
2 | public static void main(String[] args) {
3 | System.out.println("Hello World!");
4 | System.out.println("I rule the world!");
5 |
6 | int x = 0;
7 |
8 | while (x < 10) {
9 | System.out.println("Why not? " + x);
10 | x++;
11 |
12 | if (x == 3) {
13 | System.out.println("Because x is 3");
14 | }
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/java/ImageDownloader.java:
--------------------------------------------------------------------------------
1 | import java.net.*;
2 | import java.io.*;
3 |
4 | public class ImageDownloader {
5 | public static void StreamCopier(InputStream in, OutputStream out) throws Exception {
6 | // Stick to 4K page size
7 | byte[] buffer = new byte[4096];
8 |
9 | while (true) {
10 | int bytesRead = in.read(buffer);
11 | if (bytesRead == -1) break;
12 | out.write(buffer, 0, bytesRead);
13 | }
14 | }
15 |
16 | public ImageDownloader(String location, String fileName) throws Exception {
17 | StreamCopier(new URL(location).openStream(),
18 | new FileOutputStream(fileName));
19 | }
20 |
21 | public static void main(String[] args) throws Exception {
22 | if (args.length < 2) {
23 | System.out.println("Usage: ImageDownloader URL filename");
24 | System.exit(0);
25 | }
26 |
27 | new ImageDownloader(args[0], args[1]);
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/java/PhraseOMatic.java:
--------------------------------------------------------------------------------
1 | public class PhraseOMatic {
2 | public static void main(String[] args) {
3 | String[] wordlist1 = { "Say Goodnight",
4 | "To",
5 | "The",
6 | "Bad Guy" };
7 |
8 | int random = (int) (Math.random() * wordlist1.length);
9 |
10 | System.out.println("Random = " + random);
11 | System.out.println("Length = " + wordlist1.length);
12 | System.out.println(wordlist1[random]);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/java/SearchMap.java:
--------------------------------------------------------------------------------
1 | import java.util.Map;
2 | import java.util.HashMap;
3 |
4 | public class TreeNode {
5 | private TreeNode left;
6 | private TreeNode right;
7 | private String name;
8 | private Object value;
9 |
10 | TreeNode(String name) {
11 | name = name;
12 | left = null;
13 | right = null;
14 | }
15 |
16 | TreeNode(String name, TreeNode l, TreeNode r) {
17 | name = name;
18 | left = l;
19 | right = r;
20 | }
21 |
22 | void Dump() {
23 | if (left != null) {
24 | left.Dump();
25 | }
26 |
27 | if (right != null) {
28 | right.Dump();
29 | }
30 |
31 | System.out.println(name);
32 | }
33 | }
34 |
35 | public class SearchMap {
36 | public static void main(String[] args) {
37 | Map