├── .gitignore ├── README.md ├── arduino └── servo.ino ├── armasm └── argv │ ├── .gitignore │ ├── Makefile │ ├── README.md │ └── main.s ├── c ├── breakme.c └── pcap.c ├── cpp └── lrvalue.cpp ├── go ├── auth.go ├── edit_distance.go ├── knapsack.go └── word_wrap.go ├── haskell └── CountLeadingOnes.hs ├── j ├── euler │ ├── euler001.ijs │ ├── euler002.ijs │ ├── euler003.ijs │ ├── euler004.ijs │ ├── euler005.ijs │ ├── euler006.ijs │ ├── euler007.ijs │ ├── euler008.ijs │ ├── euler009.ijs │ ├── euler010.ijs │ ├── euler013.ijs │ ├── euler014.ijs │ ├── euler016.ijs │ ├── euler020.ijs │ ├── euler024.ijs │ └── euler041.ijs ├── fb_imperative.ijs ├── jtalk │ ├── .gitignore │ ├── apllife.png │ ├── examples.txt │ ├── jtalk.pdf │ └── jtalk.tex ├── knn.ijs ├── palindrome.ijs └── sum_cli.ijs ├── js ├── hubot │ ├── sexpr.coffee │ └── substitution.coffee └── phantomjs │ └── scrape.js ├── python ├── person_unittest │ ├── person.py │ └── person_test.py ├── square_property │ ├── square.py │ └── square_test.py └── street_view_api.py ├── rust └── weather.rs └── sh ├── qsort ├── README ├── qsort.sh ├── qsort_test.sh └── qsortv.sh └── search_contents.sh /.gitignore: -------------------------------------------------------------------------------- 1 | *.swp 2 | \#*# 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | snippets 2 | =================== 3 | -------------------------------------------------------------------------------- /arduino/servo.ino: -------------------------------------------------------------------------------- 1 | #include 2 | Servo Pan, Tilt; // Define our Servo 3 | int tv = 50, pv = 0; 4 | 5 | void setup() 6 | { 7 | Pan.attach(10); 8 | Pan.write(pv); 9 | Tilt.attach(11); 10 | Tilt.write(tv); 11 | 12 | Serial.begin(9600); 13 | Serial.println("Ready"); 14 | 15 | } 16 | 17 | void loop() 18 | { 19 | if (Serial.available()) { 20 | char c = Serial.read(); 21 | 22 | switch (c) { 23 | case 'w': 24 | tv += 5; 25 | Serial.println("up"); 26 | break; 27 | case 's': 28 | tv -= 5; 29 | Serial.println("down"); 30 | break; 31 | case 'a': 32 | pv += 5; 33 | Serial.println("left"); 34 | break; 35 | case 'd': 36 | pv -= 5; 37 | Serial.println("right"); 38 | break; 39 | case ' ': 40 | tv = 50; 41 | pv = 0; 42 | Serial.println("cleard"); 43 | break; 44 | default: 45 | break; 46 | } 47 | 48 | Tilt.write(tv); 49 | Pan.write(pv); 50 | } 51 | delay(20); 52 | } 53 | -------------------------------------------------------------------------------- /armasm/argv/.gitignore: -------------------------------------------------------------------------------- 1 | *.o 2 | argv 3 | -------------------------------------------------------------------------------- /armasm/argv/Makefile: -------------------------------------------------------------------------------- 1 | TARGET = argv 2 | AS = armv6j-hardfloat-linux-gnueabi-as 3 | LD = armv6j-hardfloat-linux-gnueabi-ld 4 | ASFLAGS = 5 | LDLAGS = 6 | 7 | SOURCES := main.s 8 | HEADERS := 9 | OBJECTS := $(SOURCES:%.s=%.o) 10 | 11 | EMU = qemu-arm 12 | EMUFLAGS = -L /usr/armv6j-hardfloat-linux-gnueabi/ 13 | EMUDB = -g 9000 14 | 15 | all: $(TARGET) 16 | 17 | $(TARGET): $(OBJECTS) 18 | $(LD) -o $@ $(LDLAGS) $(OBJECTS) 19 | 20 | $(OBJECTS): %.o : %.s $(HEADERS) 21 | $(AS) $(ASFLAGS) -c $< -o $@ 22 | 23 | .PHONEY: clean 24 | clean: 25 | $(RM) $(OBJECTS) $(TARGET) 26 | 27 | .PHONEY: run 28 | run: $(TARGET) 29 | $(EMU) $(EMUFLAGS) $(TARGET) 30 | 31 | .PHONEY: debug 32 | debug: $(TARGET) 33 | $(EMU) $(EMUFLAGS) $(EMUDB) $(TARGET) 34 | -------------------------------------------------------------------------------- /armasm/argv/README.md: -------------------------------------------------------------------------------- 1 | argv 2 | ==== 3 | 4 | This program is written in armv6 assembler for Linux. It prints out command line 5 | arguments separated by newline characters, including the program name. The 6 | included Makefile uses qemu and an armv6-targeted `as` to allow for 7 | compilation/execution on a x86_64 host. 8 | 9 | # requirements to run on x86_64 10 | - `qemu-arm` 11 | - `as` with armv6 target 12 | - (optional) `gdb` with armv6 target for debugging 13 | 14 | It may be necessary to change the executable names in the Makefile to match 15 | the local system binaries. 16 | 17 | # running 18 | make run 19 | # to run with arguments, copy the output and append desired arguments 20 | 21 | # debugging 22 | make debug 23 | gdb argv # in another terminal 24 | (gdb) target remote localhost:9000 25 | (gdb) disas 26 | 27 | # resources 28 | inspired by: 29 | http://www.elliotbradbury.com/x86-assembly-string-length-command-line-arguments 30 | 31 | ARM Reference: 32 | http://ozark.hendrix.edu/~burch/cs/230/arm-ref.pdf 33 | 34 | Writing ARM Assembler Language: 35 | http://infocenter.arm.com/help/topic/com.arm.doc.dui0204j/DUI0204J_rvct_assembler_guide.pdf 36 | 37 | ARM Procedure Call Standard: 38 | http://infocenter.arm.com/help/topic/com.arm.doc.ihi0042e/IHI0042E_aapcs.pdf 39 | 40 | ARM EABI: new syscall entry convention: 41 | http://www.arm.linux.org.uk/developer/patches/viewpatch.php?id=3105/4 42 | 43 | syscall numbers (for me) found in: 44 | /usr/armv6j-hardfloat-linux-gnueabi/usr/include/asm/unistd.h 45 | 46 | -------------------------------------------------------------------------------- /armasm/argv/main.s: -------------------------------------------------------------------------------- 1 | 2 | .data 3 | 4 | LF: .string "\n" 5 | 6 | .text 7 | 8 | .global _start 9 | _start: 10 | pop { r0 } 11 | b printargv 12 | 13 | printargv: 14 | pop { r0 } 15 | tst r0, r0 16 | beq exit 17 | bl echol 18 | b printargv 19 | 20 | echol: 21 | mov ip, sp 22 | stmfd sp!, {fp, ip, lr} 23 | sub fp, ip, #4 24 | 25 | push { r0 } 26 | bl strlen 27 | pop { r1 } @ const void *buf = pop() 28 | mov r2, r0 @ size_t count = strlen(r0) 29 | mov r0, #1 @ int fd = 1 (stdout) 30 | mov r7, #4 @ write() syscall 31 | swi #0 32 | 33 | mov r0, #1 34 | ldr r1, =LF 35 | mov r2, #1 36 | swi #0 37 | 38 | 39 | ldmfd sp, {fp, sp, lr} 40 | bx lr 41 | 42 | strlen: 43 | mov r1, r0 @ counter 44 | strlen_loop: 45 | ldrb r2, [r1] 46 | tst r2, r2 47 | beq strlen_exit 48 | add r1, r1, #1 49 | b strlen_loop 50 | strlen_exit: 51 | sub r0, r1, r0 52 | bx lr 53 | 54 | exit: 55 | mov r0, #0 @ int status = 0 56 | mov r7, #1 @ _exit() syscall 57 | swi #0 58 | 59 | -------------------------------------------------------------------------------- /c/breakme.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void trap() 5 | { 6 | puts("it's a trap!"); 7 | exit(EXIT_FAILURE); 8 | } 9 | 10 | void load() 11 | { 12 | int i = 0xdeadbeef; 13 | int j = 0xc0ffee; 14 | long int k = 0xba173d; 15 | long int l = 0xBADCAFE; 16 | i = i; 17 | j = j; 18 | k = k; 19 | l = l; 20 | } 21 | 22 | int main() 23 | { 24 | long int x = 0xBADF00D; 25 | load(); 26 | puts("safely back to main!"); 27 | return x; 28 | } 29 | 30 | -------------------------------------------------------------------------------- /c/pcap.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(int argc, char *argv[]) 5 | { 6 | char *dev, errbuf[PCAP_ERRBUF_SIZE]; 7 | 8 | dev = pcap_lookupdev(errbuf); 9 | if (dev == NULL) { 10 | fprintf(stderr, "Couldn't find default device: %s\n", errbuf); 11 | return(2); 12 | } 13 | printf("Device: %s\n", dev); 14 | return(0); 15 | } 16 | 17 | -------------------------------------------------------------------------------- /cpp/lrvalue.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | (std::string("a") = std::string("b")) = std::string("c"); 7 | std::cout << str << std::endl; 8 | return 0; 9 | } 10 | -------------------------------------------------------------------------------- /go/auth.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net/http" 7 | ) 8 | 9 | type Manager struct { 10 | ID int64 11 | CanHire bool 12 | CanFire bool 13 | } 14 | 15 | type Employee struct { 16 | ID int64 17 | ManagerID int64 18 | Title string 19 | Salary float64 20 | } 21 | 22 | type User struct { 23 | ID int64 24 | Email string 25 | PasswordHash string 26 | } 27 | 28 | // User if the request has a valid user session, nil and error otherwise 29 | func RequestToUser(r *http.Request) (*User, error) { 30 | return &User{Email: "person@company.com", PasswordHash: "0xdeadbeef"}, nil 31 | } 32 | 33 | // Manager role if the User has one, nil and error otherwise 34 | func (u User) GetManager() (*Manager, error) { 35 | return &Manager{CanHire: true, CanFire: false}, nil 36 | } 37 | 38 | // Employee role if the User has one, nil and error otherwise 39 | func (u User) GetEmployee() (*Employee, error) { 40 | return &Employee{Title: "Paper Pusher", Salary: 100000.00}, nil 41 | } 42 | 43 | func ManagerInfo(w http.ResponseWriter, r *http.Request, m Manager) (err error) { 44 | _, err = w.Write([]byte(fmt.Sprintf("Can Hire: %v\nCan Fire: %v", m.CanHire, m.CanFire))) 45 | return err 46 | } 47 | 48 | func EmployeeInfo(w http.ResponseWriter, r *http.Request, e Employee) (err error) { 49 | _, err = w.Write([]byte(fmt.Sprintf("Title: %v\nSalary: $%0.2f", e.Title, e.Salary))) 50 | return err 51 | } 52 | 53 | func UserInfo(w http.ResponseWriter, r *http.Request, u User) (err error) { 54 | _, err = w.Write([]byte(fmt.Sprintf("Email: %v", u.Email))) 55 | return err 56 | } 57 | 58 | func main() { 59 | // AddIdentityResolverHTTP(User{}, RequestToUser) 60 | 61 | // AddRoleResolver(User.GetManager) 62 | // AddRoleResolver(User.GetEmployee) 63 | 64 | // http.Handle("/manager", AuthedHTTP(ManagerInfo)) 65 | // http.Handle("/employee", AuthedHTTP(EmployeeInfo)) 66 | // http.Handle("/user", AuthedHTTP(UserInfo)) 67 | 68 | http.Handle("/manager", managerHandler(ManagerInfo)) 69 | http.Handle("/employee", employeeHandler(EmployeeInfo)) 70 | http.Handle("/user", userHandler(UserInfo)) 71 | log.Println("Listening on :8000") 72 | err := http.ListenAndServe(":8000", nil) 73 | if err != nil { 74 | log.Fatal("ListenAndServe: ", err) 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /go/edit_distance.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func EditDistance(A []byte, B []byte) int { 6 | if len(A) == 0 { 7 | return len(B) 8 | } else if len(B) == 0 { 9 | return len(A) 10 | } else if A[0] == B[0] { 11 | return EditDistance(A[1:], B[1:]) 12 | } 13 | 14 | replaceCost := EditDistance(A[1:], B[1:]) + 1 15 | insertCost := EditDistance(A, B[1:]) + 1 16 | deleteCost := EditDistance(A[1:], B) + 1 17 | 18 | minCost := replaceCost 19 | if insertCost < minCost { 20 | minCost = insertCost 21 | } 22 | if deleteCost < minCost { 23 | minCost = deleteCost 24 | } 25 | 26 | return minCost 27 | } 28 | 29 | func main() { 30 | fmt.Println(EditDistance([]byte("SLANDER"), []byte("ISLANDER"))) 31 | } 32 | -------------------------------------------------------------------------------- /go/knapsack.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | type Item struct { 6 | size int 7 | value int 8 | } 9 | 10 | var maxValueAtSize map[int]int 11 | 12 | func MaxValue(items []Item, maxSize int) int { 13 | if _, ok := maxValueAtSize[maxSize]; ok { 14 | return maxValueAtSize[maxSize] 15 | } 16 | 17 | var maxValue int = 0 18 | for _, item := range items { 19 | if item.size <= maxSize { 20 | value := MaxValue(items, maxSize-item.size) + item.value 21 | if value > maxValue { 22 | maxValue = value 23 | } 24 | } 25 | } 26 | maxValueAtSize[maxSize] = maxValue 27 | return maxValue 28 | } 29 | 30 | func main() { 31 | maxValueAtSize = make(map[int]int) 32 | items := []Item{{2, 5}, {1, 1}, {20, 60}} 33 | fmt.Println(MaxValue(items, 102)) 34 | } 35 | -------------------------------------------------------------------------------- /go/word_wrap.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func Sum(xs []int) int { 6 | var sum int = 0 7 | for _, x := range xs { 8 | sum += x 9 | } 10 | return sum 11 | } 12 | 13 | func Badness(wordLengths []int, lineLength int) int { 14 | sum := Sum(wordLengths) 15 | var rv int = 0 16 | if sum > lineLength { 17 | rv = 10000 * (sum - lineLength) 18 | } else { 19 | t := lineLength - sum 20 | rv = t * t * t 21 | } 22 | 23 | return rv 24 | } 25 | 26 | type BadnessInput struct { 27 | wordLengths *[]int 28 | lineLength int 29 | } 30 | 31 | var badnessMemo map[BadnessInput]int 32 | 33 | func MinBadness(wordLengths []int, lineLength int) int { 34 | bi := BadnessInput{&wordLengths, lineLength} 35 | if len(wordLengths) == 0 { 36 | return 0 37 | } else if _, ok := badnessMemo[bi]; ok { 38 | return badnessMemo[bi] 39 | } 40 | 41 | var minBadness int = -1 42 | for i := 1; i < 1+len(wordLengths); i++ { 43 | badness := MinBadness(wordLengths[i:], lineLength) + 44 | Badness(wordLengths[0:i], lineLength) 45 | 46 | if minBadness < 0 || badness < minBadness { 47 | minBadness = badness 48 | } 49 | } 50 | badnessMemo[bi] = minBadness 51 | return minBadness 52 | } 53 | 54 | func main() { 55 | badnessMemo = make(map[BadnessInput]int) 56 | fmt.Println(MinBadness([]int{9, 1, 1, 2, 3, 4, 4, 6, 5, 3, 6, 4}, 10)) 57 | } 58 | -------------------------------------------------------------------------------- /haskell/CountLeadingOnes.hs: -------------------------------------------------------------------------------- 1 | import Data.List 2 | import Data.Bits 3 | import Data.Word 4 | import qualified Data.ByteString as BS 5 | 6 | -- Create a list: [(255,8),(254,7),(252,6),(248,5),...] 7 | byteAList :: [(Word8, Int)] 8 | byteAList = map (\x -> ((shift 0xFF x) .&. 0xFF, 8-x)) [0..7] 9 | 10 | -- Count how many leading ones the Word8 b has 11 | countByteLeadingOnes :: Word8 -> Int 12 | countByteLeadingOnes b = case find (\x -> (fst x) .&. b == (fst x)) byteAList of 13 | Nothing -> 0 14 | Just (x, y) -> y 15 | 16 | -- Determines if the bytestring bs has at least n leading ones 17 | hasLeadingOnes :: Int -> BS.ByteString -> Bool 18 | hasLeadingOnes n bs = hasLeadingOnes' n bs 0 19 | 20 | hasLeadingOnes' :: Int -> BS.ByteString -> Int -> Bool 21 | hasLeadingOnes' n bs count = case BS.uncons bs of 22 | Nothing -> count >= n 23 | Just (b, bs') -> hasLeadingOnes' n bs' (currentCount + count) 24 | where currentCount = countByteLeadingOnes b 25 | -------------------------------------------------------------------------------- /j/euler/euler001.ijs: -------------------------------------------------------------------------------- 1 | NB. If we list all the natural numbers below 10 that are multiples of 3 or 5, 2 | NB. we get 3, 5, 6 and 9. The sum of these multiples is 23. 3 | NB. Find the sum of all the multiples of 3 or 5 below 1000. 4 | 5 | +/(#~ ((0=3&|)+.(0=5&|))) }.i.1000 6 | 7 | -------------------------------------------------------------------------------- /j/euler/euler002.ijs: -------------------------------------------------------------------------------- 1 | NB. By considering the terms in the Fibonacci sequence whose values 2 | NB. do not exceed four million, find the sum of the even-valued terms. 3 | 4 | +/(#~ (0=2&|)) |. }. (,~ [: +/ 2&{.)^:(4e6>{.)^:_ [ 2 1 5 | 6 | -------------------------------------------------------------------------------- /j/euler/euler003.ijs: -------------------------------------------------------------------------------- 1 | NB. The prime factors of 13195 are 5, 7, 13 and 29. 2 | NB. What is the largest prime factor of the number 600851475143 ? 3 | 4 | {:q:600851475143 5 | 6 | -------------------------------------------------------------------------------- /j/euler/euler004.ijs: -------------------------------------------------------------------------------- 1 | NB. A palindromic number reads the same both ways. The largest palindrome made 2 | NB. from the product of two 2-digit numbers is 9009 = 91*99. 3 | NB. Find the largest palindrome made from the product of two 3-digit numbers. 4 | 5 | >./10#.(#~(-:|.)"1)(10&#.^:_1)~.,(100+i.900)*/(100+i.900) 6 | 7 | -------------------------------------------------------------------------------- /j/euler/euler005.ijs: -------------------------------------------------------------------------------- 1 | NB. 2520 is the smallest number that can be divided by each of the numbers 2 | NB. from 1 to 10 without any remainder. What is the smallest positive number 3 | NB. that is evenly divisible by all of the numbers from 1 to 20? 4 | 5 | *./ 1+i.20 6 | 7 | NB. brute-force version 8 | (1&+)^:(0&<@([:+/(1+i.20)&|))^:_ [ 1 9 | 10 | -------------------------------------------------------------------------------- /j/euler/euler006.ijs: -------------------------------------------------------------------------------- 1 | NB. Find the difference between the sum of the squares of the first one 2 | NB. hundred natural numbers and the square of the sum. 3 | 4 | ((+/(1+i.100))^2) - +/(1+i.100)^2 5 | 6 | -------------------------------------------------------------------------------- /j/euler/euler007.ijs: -------------------------------------------------------------------------------- 1 | NB. What is the 10001st prime number? 2 | 3 | p:10000 4 | 5 | -------------------------------------------------------------------------------- /j/euler/euler008.ijs: -------------------------------------------------------------------------------- 1 | NB. Find the greatest product of five consecutive digits in the 1000-digit number. 2 | 3 | NB. 73167176531330624919225119674426574742355349194934 4 | NB. 96983520312774506326239578318016984801869478851843 5 | NB. 85861560789112949495459501737958331952853208805511 6 | NB. 12540698747158523863050715693290963295227443043557 7 | NB. 66896648950445244523161731856403098711121722383113 8 | NB. 62229893423380308135336276614282806444486645238749 9 | NB. 30358907296290491560440772390713810515859307960866 10 | NB. 70172427121883998797908792274921901699720888093776 11 | NB. 65727333001053367881220235421809751254540594752243 12 | NB. 52584907711670556013604839586446706324415722155397 13 | NB. 53697817977846174064955149290862569321978468622482 14 | NB. 83972241375657056057490261407972968652414535100474 15 | NB. 82166370484403199890008895243450658541227588666881 16 | NB. 16427171479924442928230863465674813919123162824586 17 | NB. 17866458359124566529476545682848912883142607690042 18 | NB. 24219022671055626321111109370544217506941658960408 19 | NB. 07198403850962455444362981230987879927244284909188 20 | NB. 84580156166097919133875499200524063689912560717606 21 | NB. 05886116467109405077541002256983155200055935729725 22 | NB. 71636269561882670428252483600823257530420752963450 23 | 24 | n =: 7 3 1 6 7 1 7 6 5 3 1 3 3 0 6 2 4 9 1 9 2 2 5 1 1 9 6 7 4 4 2 6 5 7 4 7 4 2 3 5 5 3 4 9 1 9 4 9 3 4 9 6 9 8 3 5 2 0 3 1 2 7 7 4 5 0 6 3 2 6 2 3 9 5 7 8 3 1 8 0 1 6 9 8 4 8 0 1 8 6 9 4 7 8 8 5 1 8 4 3 8 5 8 6 1 5 6 0 7 8 9 1 1 2 9 4 9 4 9 5 4 5 9 5 0 1 7 3 7 9 5 8 3 3 1 9 5 2 8 5 3 2 0 8 8 0 5 5 1 1 1 2 5 4 0 6 9 8 7 4 7 1 5 8 5 2 3 8 6 3 0 5 0 7 1 5 6 9 3 2 9 0 9 6 3 2 9 5 2 2 7 4 4 3 0 4 3 5 5 7 6 6 8 9 6 6 4 8 9 5 0 4 4 5 2 4 4 5 2 3 1 6 1 7 3 1 8 5 6 4 0 3 0 9 8 7 1 1 1 2 1 7 2 2 3 8 3 1 1 3 6 2 2 2 9 8 9 3 4 2 3 3 8 0 3 0 8 1 3 5 3 3 6 2 7 6 6 1 4 2 8 2 8 0 6 4 4 4 4 8 6 6 4 5 2 3 8 7 4 9 3 0 3 5 8 9 0 7 2 9 6 2 9 0 4 9 1 5 6 0 4 4 0 7 7 2 3 9 0 7 1 3 8 1 0 5 1 5 8 5 9 3 0 7 9 6 0 8 6 6 7 0 1 7 2 4 2 7 1 2 1 8 8 3 9 9 8 7 9 7 9 0 8 7 9 2 2 7 4 9 2 1 9 0 1 6 9 9 7 2 0 8 8 8 0 9 3 7 7 6 6 5 7 2 7 3 3 3 0 0 1 0 5 3 3 6 7 8 8 1 2 2 0 2 3 5 4 2 1 8 0 9 7 5 1 2 5 4 5 4 0 5 9 4 7 5 2 2 4 3 5 2 5 8 4 9 0 7 7 1 1 6 7 0 5 5 6 0 1 3 6 0 4 8 3 9 5 8 6 4 4 6 7 0 6 3 2 4 4 1 5 7 2 2 1 5 5 3 9 7 5 3 6 9 7 8 1 7 9 7 7 8 4 6 1 7 4 0 6 4 9 5 5 1 4 9 2 9 0 8 6 2 5 6 9 3 2 1 9 7 8 4 6 8 6 2 2 4 8 2 8 3 9 7 2 2 4 1 3 7 5 6 5 7 0 5 6 0 5 7 4 9 0 2 6 1 4 0 7 9 7 2 9 6 8 6 5 2 4 1 4 5 3 5 1 0 0 4 7 4 8 2 1 6 6 3 7 0 4 8 4 4 0 3 1 9 9 8 9 0 0 0 8 8 9 5 2 4 3 4 5 0 6 5 8 5 4 1 2 2 7 5 8 8 6 6 6 8 8 1 1 6 4 2 7 1 7 1 4 7 9 9 2 4 4 4 2 9 2 8 2 3 0 8 6 3 4 6 5 6 7 4 8 1 3 9 1 9 1 2 3 1 6 2 8 2 4 5 8 6 1 7 8 6 6 4 5 8 3 5 9 1 2 4 5 6 6 5 2 9 4 7 6 5 4 5 6 8 2 8 4 8 9 1 2 8 8 3 1 4 2 6 0 7 6 9 0 0 4 2 2 4 2 1 9 0 2 2 6 7 1 0 5 5 6 2 6 3 2 1 1 1 1 1 0 9 3 7 0 5 4 4 2 1 7 5 0 6 9 4 1 6 5 8 9 6 0 4 0 8 0 7 1 9 8 4 0 3 8 5 0 9 6 2 4 5 5 4 4 4 3 6 2 9 8 1 2 3 0 9 8 7 8 7 9 9 2 7 2 4 4 2 8 4 9 0 9 1 8 8 8 4 5 8 0 1 5 6 1 6 6 0 9 7 9 1 9 1 3 3 8 7 5 4 9 9 2 0 0 5 2 4 0 6 3 6 8 9 9 1 2 5 6 0 7 1 7 6 0 6 0 5 8 8 6 1 1 6 4 6 7 1 0 9 4 0 5 0 7 7 5 4 1 0 0 2 2 5 6 9 8 3 1 5 5 2 0 0 0 5 5 9 3 5 7 2 9 7 2 5 7 1 6 3 6 2 6 9 5 6 1 8 8 2 6 7 0 4 2 8 2 5 2 4 8 3 6 0 0 8 2 3 2 5 7 5 3 0 4 2 0 7 5 2 9 6 3 4 5 0 25 | 26 | >./(*/"1)5{."1(i.(#n)-5)|."0 1/n 27 | 28 | -------------------------------------------------------------------------------- /j/euler/euler009.ijs: -------------------------------------------------------------------------------- 1 | NB. There exists exactly one Pythagorean triplet for which a + b + c = 1000. 2 | NB. Find the product abc. 3 | 4 | (i.5) (+&*:)/ i.5 NB. incomplete 5 | 6 | -------------------------------------------------------------------------------- /j/euler/euler010.ijs: -------------------------------------------------------------------------------- 1 | NB. The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. 2 | NB. Find the sum of all the primes below two million. 3 | 4 | +/p:i._1 p:2e6 5 | 6 | -------------------------------------------------------------------------------- /j/euler/euler013.ijs: -------------------------------------------------------------------------------- 1 | NB. Work out the first ten digits of the sum of the following one-hundred 50-digit numbers. 2 | 3 | NB. hacky... 4 | n =: 37107287533902102798797998220837590246510135740250x+46376937677490009712648124896970078050417018260538x+74324986199524741059474233309513058123726617309629x+91942213363574161572522430563301811072406154908250x+23067588207539346171171980310421047513778063246676x+89261670696623633820136378418383684178734361726757x+28112879812849979408065481931592621691275889832738x+44274228917432520321923589422876796487670272189318x+47451445736001306439091167216856844588711603153276x+70386486105843025439939619828917593665686757934951x+62176457141856560629502157223196586755079324193331x+64906352462741904929101432445813822663347944758178x+92575867718337217661963751590579239728245598838407x+58203565325359399008402633568948830189458628227828x+80181199384826282014278194139940567587151170094390x+35398664372827112653829987240784473053190104293586x+86515506006295864861532075273371959191420517255829x+71693888707715466499115593487603532921714970056938x+54370070576826684624621495650076471787294438377604x+53282654108756828443191190634694037855217779295145x+36123272525000296071075082563815656710885258350721x+45876576172410976447339110607218265236877223636045x+17423706905851860660448207621209813287860733969412x+81142660418086830619328460811191061556940512689692x+51934325451728388641918047049293215058642563049483x+62467221648435076201727918039944693004732956340691x+15732444386908125794514089057706229429197107928209x+55037687525678773091862540744969844508330393682126x+18336384825330154686196124348767681297534375946515x+80386287592878490201521685554828717201219257766954x+78182833757993103614740356856449095527097864797581x+16726320100436897842553539920931837441497806860984x+48403098129077791799088218795327364475675590848030x+87086987551392711854517078544161852424320693150332x+59959406895756536782107074926966537676326235447210x+69793950679652694742597709739166693763042633987085x+41052684708299085211399427365734116182760315001271x+65378607361501080857009149939512557028198746004375x+35829035317434717326932123578154982629742552737307x+94953759765105305946966067683156574377167401875275x+88902802571733229619176668713819931811048770190271x+25267680276078003013678680992525463401061632866526x+36270218540497705585629946580636237993140746255962x+24074486908231174977792365466257246923322810917141x+91430288197103288597806669760892938638285025333403x+34413065578016127815921815005561868836468420090470x+23053081172816430487623791969842487255036638784583x+11487696932154902810424020138335124462181441773470x+63783299490636259666498587618221225225512486764533x+67720186971698544312419572409913959008952310058822x+95548255300263520781532296796249481641953868218774x+76085327132285723110424803456124867697064507995236x+37774242535411291684276865538926205024910326572967x+23701913275725675285653248258265463092207058596522x+29798860272258331913126375147341994889534765745501x+18495701454879288984856827726077713721403798879715x+38298203783031473527721580348144513491373226651381x+34829543829199918180278916522431027392251122869539x+40957953066405232632538044100059654939159879593635x+29746152185502371307642255121183693803580388584903x+41698116222072977186158236678424689157993532961922x+62467957194401269043877107275048102390895523597457x+23189706772547915061505504953922979530901129967519x+86188088225875314529584099251203829009407770775672x+11306739708304724483816533873502340845647058077308x+82959174767140363198008187129011875491310547126581x+97623331044818386269515456334926366572897563400500x+42846280183517070527831839425882145521227251250327x+55121603546981200581762165212827652751691296897789x+32238195734329339946437501907836945765883352399886x+75506164965184775180738168837861091527357929701337x+62177842752192623401942399639168044983993173312731x+32924185707147349566916674687634660915035914677504x+99518671430235219628894890102423325116913619626622x+73267460800591547471830798392868535206946944540724x+76841822524674417161514036427982273348055556214818x+97142617910342598647204516893989422179826088076852x+87783646182799346313767754307809363333018982642090x+10848802521674670883215120185883543223812876952786x+71329612474782464538636993009049310363619763878039x+62184073572399794223406235393808339651327408011116x+66627891981488087797941876876144230030984490851411x+60661826293682836764744779239180335110989069790714x+85786944089552990653640447425576083659976645795096x+66024396409905389607120198219976047599490197230297x+64913982680032973156037120041377903785566085089252x+16730939319872750275468906903707539413042652315011x+94809377245048795150954100921645863754710598436791x+78639167021187492431995700641917969777599028300699x+15368713711936614952811305876380278410754449733078x+40789923115535562561142322423255033685442488917353x+44889911501440648020369068063960672322193204149535x+41503128880339536053299340368006977710650566631954x+81234880673210146739058568557934581403627822703280x+82616570773948327592232845941706525094512325230608x+22918802058777319719839450180888072429661980811197x+77158542502016545090413245809786882778948721859617x+72107838435069186155435662884062257473692284509516x+20849603980134001723930671666823555245252804609722x+53503534226472524250874054075591789781264330331690x 5 | 6 | 10#.10{.(10&#.^:_1) n 7 | 8 | -------------------------------------------------------------------------------- /j/euler/euler014.ijs: -------------------------------------------------------------------------------- 1 | NB. The following iterative sequence is defined for the set of positive integers: 2 | NB. n -> n/2 (n is even) 3 | NB. n -> 3n + 1 (n is odd) 4 | 5 | nx =: 2&| { %&2 , +&1@*&3 6 | s =: (,~ nx@{.)^:(1 ~: {.)^:_ 7 | {. s"0 ] >:i.1e6 8 | 9 | -------------------------------------------------------------------------------- /j/euler/euler016.ijs: -------------------------------------------------------------------------------- 1 | NB. 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. 2 | NB. What is the sum of the digits of the number 2^1000? 3 | 4 | +/(10&#.^:_1)2^1000x 5 | 6 | -------------------------------------------------------------------------------- /j/euler/euler020.ijs: -------------------------------------------------------------------------------- 1 | NB. Find the sum of the digits in the number 100! 2 | +/(10&#.^:_1)!100x 3 | 4 | -------------------------------------------------------------------------------- /j/euler/euler024.ijs: -------------------------------------------------------------------------------- 1 | NB. What is the millionth lexicographic permutation of the digits 2 | NB. 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9? 3 | 4 | 999999 A. i.10 5 | 6 | -------------------------------------------------------------------------------- /j/euler/euler041.ijs: -------------------------------------------------------------------------------- 1 | NB. We shall say that an n-digit number is pandigital if it makes use of all 2 | NB. the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital 3 | NB. and is also prime. 4 | NB. What is the largest n-digit pandigital prime that exists? 5 | 6 | >./(#~1&p:)10#.(i.!7)A.1+i.7 7 | 8 | -------------------------------------------------------------------------------- /j/fb_imperative.ijs: -------------------------------------------------------------------------------- 1 | FB =: 3 : 0 2 | x =: 1 3 | p =: 0$0 4 | while. x < 101 do. 5 | if. 0=15|x do. 6 | p =: p,<'FizzBuzz' 7 | elseif. 0=3|x do. 8 | p =: p,<'Fizz' 9 | elseif. 0=5|x do. 10 | p =: p,<'Buzz' 11 | elseif. 1 do. 12 | p =: p,<":x 13 | end. 14 | x =: x + 1 15 | end. 16 | >p 17 | ) 18 | 19 | -------------------------------------------------------------------------------- /j/jtalk/.gitignore: -------------------------------------------------------------------------------- 1 | *.aux 2 | *.nav 3 | *.log 4 | *.out 5 | *.snm 6 | *.toc 7 | -------------------------------------------------------------------------------- /j/jtalk/apllife.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wyc/snippets/cd5cd0fb89892a691b6f7db614c967a622b327fa/j/jtalk/apllife.png -------------------------------------------------------------------------------- /j/jtalk/examples.txt: -------------------------------------------------------------------------------- 1 | NB. Sum: add up 1 2 3 4 5 2 | +/ 1 2 3 4 5 3 | NB. Vector Magnitude: find the magnitude of the 3D vector <5, 8, 9> (uses 4 | bonding[0]) 5 | %:+/^&2 ] 5 8 9 6 | NB. Vector Normalization: normalize the 4D vector <5, 5, 5, 8> (uses a 7 | hook[0]) 8 | (%+/) 5 5 5 8 9 | NB. Taxes: 5% tax on 100 (uses a hook and bonding) 10 | (+*&0.05) 100 11 | NB. Arithmetic Mean: mean of 50, 100, 150, 200, and 8 (uses a fork[0]) 12 | (+/%#) 50 100 150 200 8 13 | NB. 1D Convolution: convolve [0 1 0 0 1 0 0 1 0] with kernel [0.25 0.5 0.25] 14 | (" is the rank operator....a bit more advanced than we were able to get to[1]. 15 | read up on convolution and edge filters if you want to learn more about the 16 | math[2].) 17 | +/0.25 0.5 0.25 * _1 0 1 |."(0 _) 0 1 0 0 1 0 0 1 0 18 | NB. FizzBuzz: 19 | FB=:((0 i.~15 3 5|]){::'FizzBuzz';'Fizz';'Buzz';": )"0 20 | FB >:i.100 21 | J Vocabulary: 22 | http://www.jsoftware.com/help/dictionary/vocabul.htm 23 | An important concept I forgot to mention during the talk: 24 | As programming languages evolve, we use fewer variables. Compare assembler to 25 | C, and then C to Python. These tools become more powerful because they allow 26 | us to be less concerned with the implementation details and more so with 27 | expression of algorithms and their semantic meanings. Consider doubling a 28 | list's members without the use of libraries: 29 | C: 30 | int i, a[] = {1, 2, 3, 4 ,5}; 31 | for (i = 0; i < 5; i++) { 32 | a[i] = a[i] * 2; 33 | } 34 | Python: 35 | list(map(lambda x: x * 2, [1, 2, 3, 4, 5])) 36 | J: 37 | +: 1 2 3 4 5 38 | Because J is array-based (think matlab, octave, or R), you can go as many as 39 | 128 dimensions without changing the code. 40 | Happy hacking! 41 | - Wayne 42 | [0] http://www.jsoftware.com/help/learning/03.htm 43 | [1] http://www.jsoftware.com/help/learning/07.htm 44 | [2] 45 | http://www.cs.cornell.edu/courses/CS1114/2013sp/sections/S06_convolution.pdf 46 | -------------------------------------------------------------------------------- /j/jtalk/jtalk.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wyc/snippets/cd5cd0fb89892a691b6f7db614c967a622b327fa/j/jtalk/jtalk.pdf -------------------------------------------------------------------------------- /j/jtalk/jtalk.tex: -------------------------------------------------------------------------------- 1 | \documentclass{beamer} 2 | \begin{document} 3 | \title{Introduction to the J Programming Language} 4 | \author{Wayne Chang} 5 | \date{\today} 6 | 7 | \frame{\titlepage} 8 | 9 | \frame{\frametitle{Table of contents}\tableofcontents} 10 | 11 | 12 | \section{History} 13 | \subsection{What is J?} 14 | \frame{\frametitle{What is J?} 15 | 16 | J is a programming language that is: 17 | \begin{itemize} 18 | \item Functional 19 | \begin{itemize} 20 | \item Higher-order functions 21 | \item Immutable Data 22 | \end{itemize} 23 | \item Dynamic 24 | \begin{itemize} 25 | \item Dynamically typed 26 | \item Parsing tightly coupled with evaluation 27 | \end{itemize} 28 | \item Array-based 29 | \begin{itemize} 30 | \item Arrays (matrices) are first-class citizens 31 | \item Operators can all operate in higher dimensions 32 | \end{itemize} 33 | \item Tacit 34 | \begin{itemize} 35 | \item Most operations are function composition 36 | \item Higher-order function everywhere 37 | \item Learn where parameters go 38 | \end{itemize} 39 | \end{itemize} 40 | } 41 | 42 | \subsection{Why J?} 43 | \frame{\frametitle{Why J?} 44 | \begin{itemize} 45 | \item Operations on Matrices 46 | \item Mathematical and Statistical Programming 47 | \item Signal Processing 48 | \item Examples 49 | \begin{itemize} 50 | \item Financial and Insurance Risk Calculations 51 | \item Network Flow Analysis 52 | \item Polling Institutions 53 | \item Econometrics 54 | \end{itemize} 55 | \end{itemize} 56 | } 57 | 58 | \subsection{Spiritual Successor to APL} 59 | \frame{\frametitle{Spiritual Successor to APL} 60 | \begin{itemize} 61 | \item Stands for ``A Programming Language'' 62 | \item Developed in the 1960s by Kenneth E. Iverson 63 | \item Not a Von Neumann language (isomorph of the machine) 64 | \item Conway's Game of Life in one line of APL: 65 | \includegraphics[scale=0.5]{apllife} 66 | \item J was developed in the early 1990's by Ken Iverson and Roger Hui 67 | \end{itemize} 68 | } 69 | 70 | \section{The Language} 71 | \subsection{Terminology and Examples} 72 | \frame{\frametitle{Terminology: Nouns, Verbs, Adverbs, Operators} 73 | \begin{itemize} 74 | \item Right-to-left evaluation 75 | \item Nouns are data like 100, ``hello, world!'', and 1.333 76 | \item Verbs are ordinary functions like $+$ or $-$ 77 | \item Adverbs and operators are functions that compute functions from functions 78 | \end{itemize} 79 | } 80 | 81 | \frame{\frametitle{Monads and Dyads} 82 | \begin{itemize} 83 | \item Monads are verbs that take one argument on the right: $*: 4$ 84 | \item Dyads are verbs that take one argument each side: $2 + 2$ 85 | \item The same symbol has multiple meanings depending on the context 86 | \end{itemize} 87 | \begin{tabular}{|c|c|c|} 88 | \hline 89 | \textbf{Symbol} & \textbf{Monadic} & \textbf{Dyadic} \\ 90 | \hline 91 | + & Conjugate & Plus \\ 92 | \hline 93 | $-$ & Negate & Minus \\ 94 | \hline 95 | $<.$ & Integral Floor & Lesser of \\ 96 | \hline 97 | $|$ & Magnitude & Residue \\ 98 | \hline 99 | \end{tabular} 100 | } 101 | 102 | 103 | \frame{\frametitle{Arrays and Boxes} 104 | \begin{itemize} 105 | \item Different from arrays in other programming languages. 106 | \item A table is a 2-dimensional array. 107 | \item Arrays have rank and shape. 108 | \item Cue array example: shape, tally \#, index of/integers (i.), join (,), from (\{), match ($-:$) 109 | \item Cue box example: open ($>$), box ($<$) 110 | \end{itemize} 111 | } 112 | 113 | \frame{\frametitle{Examples} 114 | \begin{itemize} 115 | \item sum, product (introducing the / operator) 116 | \item vector magnitude (introducting bonding with \&) 117 | \item taxes and percentages (introducing hooks) 118 | \item mean (introducing forks) 119 | \item 1D kernel convolution 120 | \item stateless FizzBuzz 121 | \item various euler problems 122 | \item introspection with 5!:4, 7!:2, 6!:2 123 | \end{itemize} 124 | } 125 | 126 | \end{document} 127 | 128 | -------------------------------------------------------------------------------- /j/knn.ijs: -------------------------------------------------------------------------------- 1 | NB. naive k-nearest neighbors in J 2 | 3 | dist =: [:%:[:|[:+/(*:@:-) NB. dyad takes two vectors, returns euclidean distance 4 | 5 | data =: 1 2 3,2 2 3,2 3 3,1 2 3,:2 3 4 6 | query =: 1 2 3 7 | k =: 3 8 | 9 | k {."1 /:"1 query&dist"1 data 10 | 11 | -------------------------------------------------------------------------------- /j/palindrome.ijs: -------------------------------------------------------------------------------- 1 | NB. 1 if input string argument is a palindrome, 0 otherwise 2 | isPalindrome =: (-:|.) 3 | 4 | -------------------------------------------------------------------------------- /j/sum_cli.ijs: -------------------------------------------------------------------------------- 1 | #!/opt/j/bin/jconsole 2 | 3 | echo +/*:0".>,.2}.ARGV 4 | exit'' -------------------------------------------------------------------------------- /js/hubot/sexpr.coffee: -------------------------------------------------------------------------------- 1 | # Description: 2 | # Evaluate Simple S-Expressions 3 | # 4 | # Dependencies: 5 | # None 6 | # 7 | # Commands: 8 | # See definition of @symbols 9 | # e.g. 10 | # (+ 1 (+ 1 2)) 11 | # (append abc efg) 12 | # (if (= 1 1) correct incorrect) 13 | # 14 | # 15 | # Features: 16 | # As many unmatched )'s as you'd like. 17 | # No type enforcement 18 | # No variables yet 19 | # 20 | # Author: 21 | # wyc 22 | 23 | class Sexpr 24 | 25 | constructor: (@robot) -> 26 | @symbols = { 27 | 'car': (xs) -> xs[0] 28 | 'cdr': (xs) -> xs[1..] 29 | '+': (x, y) -> x + y 30 | '-': (x, y) -> x - y 31 | '*': (x, y) -> x * y 32 | '/': (x, y) -> x / y 33 | '%': (x, y) -> x % y 34 | 'sum': (xs) -> xs.reduce (x, y) -> x + y 35 | 'append': (x, y) -> x.concat(y) 36 | 'concat': (xs) -> xs.reduce (x, y) -> x.concat(y) 37 | '=': (x, y) -> x == y 38 | '<': (x, y) -> x < y 39 | '<=': (x, y) -> x <= y 40 | '>': (x, y) -> x > y 41 | '>=': (x, y) -> x >= y 42 | # @todo add karma features 43 | } 44 | 45 | @lazySymbols = { 46 | 'if': (x, y, z) -> if this.eval(x) then this.eval(y) else this.eval(z) 47 | } 48 | 49 | eval: (ast) -> 50 | if ast[0] of @symbols 51 | p = []; p[i] = this.eval(v) for v, i in ast[1..] 52 | @symbols[ast[0]].apply(this, p) 53 | else if ast[0] of @lazySymbols 54 | @lazySymbols[ast[0]].apply(this, ast[1..]) 55 | else if ast instanceof Array 56 | p = []; p[i] = this.eval(v) for v, i in ast; p 57 | else ast 58 | 59 | parse: (ts) -> 60 | throw "unmatched (" if ts.length == 0 61 | t = ts.shift() 62 | if t == '(' 63 | list = []; list.push(this.parse(ts)) while ts[0] != ')' 64 | ts.shift() 65 | list 66 | else 67 | if t of @symbols then t 68 | else if t.match /^-?[0-9]+\.[0-9]+$/ then parseFloat t 69 | else if t.match /^-?[0-9]+$/ then parseInt t 70 | else "#{t}" 71 | 72 | tokenize: (s) -> 73 | ts = s.replace(/\(/g, ' ( ').replace(/\)/g, ' ) ').split(' ') 74 | ts.splice(i, 1) while (i = ts.indexOf('')) != -1 75 | ts 76 | 77 | toString: (r) -> 78 | if r instanceof Array 79 | s = '( '; s += "#{this.toString(v)} " for v in r; s += ')'; s 80 | else 81 | "#{r}" 82 | 83 | module.exports = (robot) -> 84 | sexpr = new Sexpr robot 85 | robot.respond /(\(.*?\))$/, (msg) -> 86 | match = msg.match[1] # msg.match[1].toLowerCase() 87 | try 88 | ts = sexpr.tokenize match 89 | ast = sexpr.parse ts.slice(0) 90 | result = sexpr.eval(ast) 91 | s = sexpr.toString(result) 92 | msg.send "#{msg.message.user.name}: #{s}" 93 | catch e 94 | msg.send "#{msg.message.user.name}: #{e}" 95 | 96 | -------------------------------------------------------------------------------- /js/hubot/substitution.coffee: -------------------------------------------------------------------------------- 1 | # Description: 2 | # say what you mean to say 3 | # 4 | # Dependencies: 5 | # None 6 | # 7 | # Configuration: 8 | # None 9 | # 10 | # Commands: 11 | # s/// - correct yourself 12 | # user: s/// - correct someone else 13 | # 14 | # Author: 15 | # wyc 16 | 17 | class Substitution 18 | 19 | constructor: (@robot) -> 20 | @lastLine = {} 21 | @pattern = /^(?:([^\s]+)?(?:: ))?s\/([^\/\\]*(?:\\.[^\/\\]*)*)\/([^\/\\]*(?:\\.[^\/\\]*)*)(?:\/(.*))?/ 22 | @verbs = [ "actually meant to say", "meant to say", "really meant to say" ] 23 | 24 | setLastLine: (user, line) -> 25 | @lastLine[user] = line 26 | 27 | getLastLine: (user) -> 28 | return if @lastLine[user]? then @lastLine[user] else '' 29 | 30 | verb: -> 31 | @verbs[Math.floor(Math.random() * @verbs.length)] 32 | 33 | module.exports = (robot) -> 34 | substitution = new Substitution robot 35 | robot.hear substitution.pattern, (msg) -> 36 | target = msg.match[1] 37 | query = msg.match[2].replace /\\\//g, '/' 38 | replace = msg.match[3].replace /\\\//g, '/' 39 | flags = msg.match[4] 40 | 41 | try 42 | [prefix, user] = if target? then ["#{msg.message.user.name} thinks ", target] else ["", msg.message.user.name] 43 | lastLine = substitution.getLastLine(user); 44 | queryPattern = new RegExp(query, if flags? then flags else ''); 45 | response = lastLine.replace queryPattern, replace 46 | 47 | if response != '' && response != lastLine 48 | substitution.setLastLine(msg.message.user.name, response) unless target?; 49 | msg.send "#{prefix}#{user} #{substitution.verb()}: #{response}" 50 | catch error 51 | msg.send "#{msg.message.user.name}, bad regex; #{error}" 52 | 53 | robot.hear /.*/, (msg) -> 54 | unless substitution.pattern.test(msg.match[0]) 55 | substitution.setLastLine(msg.message.user.name, msg.match[0]) 56 | 57 | 58 | -------------------------------------------------------------------------------- /js/phantomjs/scrape.js: -------------------------------------------------------------------------------- 1 | var system = require('system'); 2 | var page = require('webpage').create(); 3 | var tableID = system.args[2]; 4 | page.open(system.args[1], function() { 5 | var rv = page.evaluate(function(tableID) { 6 | function strim(str) { return str.replace(/(\r\n|\n|\r|\t)/gm," ").replace(/\s+/g," "); } 7 | var tb = document.getElementById(tableID).firstElementChild; 8 | var hr = tb.firstElementChild; 9 | var headers = []; 10 | for (var i = 0; i < hr.childElementCount; i++) { 11 | headers.push(strim(hr.children[i].textContent)); 12 | } 13 | headers[0] = 'Details'; 14 | 15 | var rows = []; 16 | for (var tr = hr.nextSibling; tr; tr = tr.nextSibling) { 17 | var rowData = {}; 18 | for (var i = 0; i < tr.childElementCount; i++) { 19 | if (i == 0) { 20 | rowData[headers[i]] = tr.children[i].getElementsByTagName('a')[0].getAttribute("href"); 21 | } else { 22 | rowData[headers[i]] = strim(tr.children[i].textContent); 23 | } 24 | } 25 | rows.push(rowData); 26 | } 27 | return rows; 28 | }, tableID); 29 | console.log(JSON.stringify(rv, null, 2)); 30 | phantom.exit(); 31 | }); 32 | -------------------------------------------------------------------------------- /python/person_unittest/person.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | class Person: 4 | def __init__(self, name, gender, age): 5 | self.name = name 6 | self.gender = gender 7 | self.age = age 8 | 9 | def __str__(self): 10 | return "%s: %s (%d)" % (self.name, self.gender, self.age) 11 | 12 | -------------------------------------------------------------------------------- /python/person_unittest/person_test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | from person import Person 4 | import unittest 5 | 6 | class Tests(unittest.TestCase): 7 | def setUp(self): 8 | self.p = Person("George Smith", "male", 42) 9 | 10 | def test_name(self): 11 | self.assertEqual(self.p.name, "George Smith") 12 | 13 | def test_bad_age(self): 14 | # should raise an exception for non-integral age 15 | self.p.age = "frogs" 16 | self.assertRaises(TypeError, Person.__str__, self.p) 17 | 18 | def tearDown(self): 19 | del self.p 20 | 21 | if __name__ == '__main__': 22 | unittest.main() 23 | 24 | -------------------------------------------------------------------------------- /python/square_property/square.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import math 4 | 5 | # new-style classes inherit from object 6 | class Square(object): 7 | def __init__(self, side): 8 | self.side = side 9 | 10 | @property 11 | def area(self): 12 | return self.side * self.side 13 | 14 | @area.setter 15 | def area(self, area): 16 | self.side = math.sqrt(area) 17 | 18 | # @area.deleter is not used 19 | 20 | -------------------------------------------------------------------------------- /python/square_property/square_test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | from square import Square 4 | import unittest 5 | 6 | class Tests(unittest.TestCase): 7 | def setUp(self): 8 | self.sq = Square(10) 9 | 10 | def test_get_area(self): 11 | self.assertEqual(self.sq.area, 10*10) 12 | 13 | def test_set_area(self): 14 | self.sq.area = 16 15 | self.assertEqual(self.sq.area, 16) 16 | self.assertEqual(self.sq.side, 4) 17 | 18 | def tearDown(self): 19 | del self.sq 20 | 21 | if __name__ == '__main__': 22 | unittest.main() 23 | 24 | -------------------------------------------------------------------------------- /python/street_view_api.py: -------------------------------------------------------------------------------- 1 | import urllib 2 | import urllib2 3 | 4 | baseurl = "http://maps.googleapis.com/maps/api/streetview" 5 | api_key = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' 6 | 7 | 8 | def getImage(latitude, longitude): 9 | #gets set of 4 images (N,S,E,W) from google 10 | values = {'size': '640x640', 'location': str(latitude) 11 | + "," + str(longitude), 12 | 'heading': 0, 13 | 'key': api_key, 14 | 'sensor': 'false' 15 | } 16 | for i in range(0, 359): 17 | values['heading'] = str(i) 18 | data = urllib.urlencode(values) 19 | full_url = baseurl + '?' + data 20 | print full_url 21 | response = urllib2.urlopen(full_url) 22 | 23 | img = response.read() 24 | imgfilename = "heading" 25 | if i < 10: 26 | imgfilename += "0" 27 | if i < 100: 28 | imgfilename += "0" 29 | imgfilename += str(i) + ".jpeg" 30 | f = open(imgfilename, 'w') 31 | 32 | f.write(img) 33 | print data 34 | print imgfilename 35 | print i 36 | 37 | 38 | def getImages(minlat, minlong, maxlat, maxlong): 39 | imgs = [] 40 | m = (maxlong - minlong) / (maxlat - minlat) 41 | b = maxlong - maxlat*m 42 | x = minlat 43 | while x < maxlat: 44 | imgs.append(getImage(x, m*x + b)) 45 | x = x + 0.000001 46 | 47 | return imgs 48 | 49 | minlat = 48.853542 50 | maxlat = 48.853742 51 | minlong = 2.347699 52 | maxlong = 2.347899 53 | #res = getImages(maxlat, maxlong, minlat, minlong) 54 | #getImage(48.853642, 2.347799) 55 | #getImage(40.707295, -74.012071) 56 | getImage(41.89128,12.491329) 57 | -------------------------------------------------------------------------------- /rust/weather.rs: -------------------------------------------------------------------------------- 1 | /** 2 | * rust network client example updated from 3 | * http://www.darkcoding.net/software/rust-what-i-learnt-so-far/#connect_to_a_socket 4 | * 5 | * rust 0.12.0 6 | */ 7 | 8 | extern crate std; 9 | 10 | use std::io::{TcpStream, IoResult}; 11 | use std::str; 12 | 13 | fn fetch(code: &str) -> IoResult> { 14 | let mut stream = TcpStream::connect("205.156.51.232", 80); 15 | let data_get = format!( 16 | "GET /pub/data/observations/metar/decoded/{}.TXT HTTP/1.1\n", 17 | code); 18 | let data_headers = "Host: weather.noaa.gov\n\n"; 19 | 20 | /* we can use try!() here, but for this example we won't use macros */ 21 | match stream.write(data_get.as_bytes()) { 22 | Ok(_) => (), 23 | Err(err) => return Err(err) 24 | } 25 | match stream.write(data_headers.as_bytes()) { 26 | Ok(_) => (), 27 | Err(err) => return Err(err) 28 | } 29 | let rv = stream.read_to_end(); 30 | 31 | /* just to show how to explicitly close the connection. 32 | * drop() is called anyway when a variable goes out of scope. */ 33 | drop(stream); 34 | 35 | return rv; 36 | } 37 | 38 | fn main() { 39 | match fetch("KEWR") { 40 | Ok(v) => println!("{}", match str::from_utf8(v.as_slice()){ 41 | Some(s) => s, 42 | None => "" 43 | }), 44 | Err(err) => println!("error: {}", err) 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /sh/qsort/README: -------------------------------------------------------------------------------- 1 | qsort implemented in 3 lines of shell, with tests. 2 | 3 | qsort.sh - implementation 4 | qsortv.sh - verbose implementation 5 | qsort_test.sh - test 6 | -------------------------------------------------------------------------------- /sh/qsort/qsort.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # qsort N1 [N2] [N3] [N4] ... 4 | qsort() 5 | { 6 | local L=""; local G=""; [ $# -eq 1 ] && echo $1 && return; 7 | P=$1; shift; for i in $@; do [ $i -lt $P ] && L="$L $i" || G="$G $i"; done 8 | [ -z "$L" ] || L=`qsort $L`; [ -z "$G" ] || G=`qsort $G`; echo "$L $P $G" 9 | } 10 | 11 | qsort $@ 12 | 13 | -------------------------------------------------------------------------------- /sh/qsort/qsort_test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | SCRIPT="./qsort.sh" 4 | TESTS=20 5 | 6 | trimws() 7 | { 8 | echo $* | sed 's/^ *//g' | sed 's/ *$//g' 9 | } 10 | 11 | qsort_test() 12 | { 13 | [ -e "$SCRIPT" ] || (echo "$0: no script file '$SCRIPT'" 1>&2; exit -1) 14 | for i in `seq $TESTS`; do 15 | local U="" 16 | for j in `seq $(($RANDOM%100+1))`; do 17 | U="$U $(($RANDOM%1000+1))" 18 | done 19 | RS=`printf "%s\n" $U | sort -n` 20 | RS=`trimws $RS` 21 | TS=`$SCRIPT $U` 22 | TS=`trimws $TS` 23 | [ "$RS" = "$TS" ] || \ 24 | (echo "$0: test failed; expected '$RS', got '$TS'" 1>&2; exit -1) 25 | done 26 | echo "$TESTS rounds of randomly generated tests passed." 27 | } 28 | 29 | qsort_test 30 | 31 | -------------------------------------------------------------------------------- /sh/qsort/qsortv.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | qsort() 4 | { 5 | echo "qsort called with args: $@" 1>&2 6 | local L=""; local G=""; [ $# -eq 1 ] && echo $1 && return 0 7 | P=$1; shift; for i in $@; do 8 | echo "deciding '$i' vs. '$P'" 1>&2 9 | if [ $i -lt $P ]; then 10 | echo "adding $i to L" 1>&2 11 | L="$L $i" 12 | else 13 | echo "adding $i to G" 1>&2 14 | G="$G $i" 15 | fi 16 | done 17 | 18 | if [ $(wc -w<<<$L) -gt 0 ]; then 19 | echo "L has members: $L" 1>&2 20 | L=`qsort $L` 21 | fi 22 | if [ $(wc -w<<<$G) -gt 0 ]; then 23 | echo "G has members: $G" 1>&2 24 | G=`qsort $G` 25 | fi 26 | 27 | echo "block sorted: $L $P $G" 1>&2 28 | echo "$L $P $G" 29 | } 30 | 31 | qsort $@ 32 | 33 | -------------------------------------------------------------------------------- /sh/search_contents.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # search contents 4 | function sc() 5 | { 6 | find . -type f -exec grep -Hn "$@" {} \; 7 | } 8 | 9 | --------------------------------------------------------------------------------