Skip to content

Instantly share code, notes, and snippets.

@nicholasbs
Created November 3, 2012 18:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicholasbs/4008267 to your computer and use it in GitHub Desktop.
Save nicholasbs/4008267 to your computer and use it in GitHub Desktop.
(define (ntbf-eval
x h d) (unless (null? x) (case
(car x) ((#\>) (ntbf-eval (cdr x) h
(+ d 1))) ((#\<) (ntbf-eval (cdr x) h
(- d 1))) ((#\+) (begin (vector-set! h d
(+ 1 (vector-ref h d))) (ntbf-eval (cdr x)
h d))) ((#\-) (begin (vector-set! h d (-
1 (vector-ref h d))) (ntbf-eval (cdr x)
h d))) ((#\.) (begin (format #t "~a" (
integer->char (vector-ref h d))) (ntbf-eval
(cdr x) h d))) (else (error "invalid non turing
brainfuck statement"))))) (define (prog-table) (let
loop ((i 0) (accum '())) (if (< i 128) (loop (+ 1 i)
(cons `(,(integer->char i) (,i #\+) (1 #\.)) accum))
accum))) (define (rld ps) (let ((char (cadr ps)))
(let loop ((i (car ps)) (accum '())) (if (> i
0) (loop (- i 1) (cons char accum)) accum)
))) (define fragments (prog-table))(define
(make-prog s) (let ((ls (string->list s)))
(let loop ((ls ls) (accum '())) (if
(not (null? ls)) (let ((p (assoc
(car ls) fragments))) (if (not
(null? p)) (loop (cdr ls) (
append accum (append (cdr
p) '((1 #\>))))) (error
"I only do ASCII"))) accum
)))) (define (decode ls) (apply
append (map rld ls))) (begin(ntbf-eval
(decode (make-prog "LinkedList NYC"))
(make-vector 100 0) 0) (newline))
;; LinkedList Ice Cream Bowl
;; By Andrew Gwozdziweycz
/*
Why try to go out and generate words when, like, you can find all the
words and letters you need in the trash, man?
This will allocate a byte of memory without initializing it and see if
what was left in there can be used to make part of the word we are
looking for. If not, it tosses it aside and goes on to the next byte.
The amount of iterations it took to find each letter as well as the
total iterations will be printed to stderr. Feel free to throw that
shit into the black hole that is /dev/null if you just want the
string.
Usage:
node recycle.js <words-to-find>
Example:
$ node recycle.js 'Sweet, half eaten sandwich!'
{ characters:
[ { chr: 'S', foundAfter: 1351 },
{ chr: 'w', foundAfter: 812 },
{ chr: 'e', foundAfter: 2121 },
{ chr: 'e', foundAfter: 2121 },
{ chr: 't', foundAfter: 1974 },
{ chr: ',', foundAfter: 1231 },
{ chr: ' ', foundAfter: 1896 },
{ chr: 'h', foundAfter: 1836 },
{ chr: 'a', foundAfter: 2102 },
{ chr: 'l', foundAfter: 1716 },
{ chr: 'f', foundAfter: 1224 },
{ chr: ' ', foundAfter: 1896 },
{ chr: 'e', foundAfter: 2121 },
{ chr: 'a', foundAfter: 2102 },
{ chr: 't', foundAfter: 1974 },
{ chr: 'e', foundAfter: 2121 },
{ chr: 'n', foundAfter: 618 },
{ chr: ' ', foundAfter: 1896 },
{ chr: 's', foundAfter: 726 },
{ chr: 'a', foundAfter: 2102 },
{ chr: 'n', foundAfter: 618 },
{ chr: 'd', foundAfter: 2113 },
{ chr: 'w', foundAfter: 812 },
{ chr: 'i', foundAfter: 271 },
{ chr: 'c', foundAfter: 1305 },
{ chr: 'h', foundAfter: 1836 },
{ chr: '!', foundAfter: 1329 } ],
bytesExamined: 2121 }
Sweet, half eaten sandwich!
Known Issues:
- If the phrase contains regexp characters that need escaping things
will fuck up.
- This can theoretically run forever if you have impeccably clean
memory.
- I kinda feel like it's cheating to reuse a single found byte for
filling in multiple holes in the string.
*/
var pathutil = require('path');
var util = require('util');
function isSparse(array) {
var len = array.length;
while (len--)
if (typeof array[len] === 'undefined')
return true;
return false;
}
function findInGarbage(words) {
// Initialize a sparse array. We'll populate it in order as we find
// discarded characters that are in totally perfect good condition,
// why would anyone throw away a character like that? People these
// days, geez.
var result = Array(words.length);
var iterations = 0;
var wordsRe = new RegExp('['+ words +']');
var chr;
while (isSparse(result) && ++iterations) {
// Dig a fresh byte of memory out of the dump and inspect it with
// your grubby, hobo-gloved hands. If it's not to your liking, just
// throw it away and move on.
chr = String.fromCharCode(Buffer(1)[0]);
if (!chr.match(wordsRe)) {
delete chr;
continue;
}
// `replace` in this context is a misnomer -- I'm just using it so I
// can get detailed information about each match, specifically the
// index it matches to in the expected string.
words.replace(new RegExp(chr, 'g'), function (chr, idx) {
result[idx] = { chr: chr, foundAfter: iterations };
return chr;
});
}
return {
characters: result,
bytesExamined: iterations
}
}
function inspect(thing) {
var color = require('tty').isatty();
return util.inspect(thing, null, null, color);
}
if (!module.parent) {
var scriptName = pathutil.basename(process.argv[1]);
var args = process.argv.slice(2);
var string, result;
if (!args.length) {
console.log('Usage: node %s <words to find>', scriptName);
process.exit(1);
}
result = findInGarbage(args[0]);
process.stderr.write(inspect(result) + '\n');
process.stdout.write(result.characters.map(function (o) {
return o.chr;
}).join('') + '\n');
process.exit(0);
}
#!/usr/bin/env python
import sys
import logging
import requests
from BeautifulSoup import BeautifulSoup
logging.basicConfig(level=logging.ERROR)
# indices of the characters of "LinkedList" in the first sentence of the
# "Greek Language" wikipedia article
indices_greek = [444, 26, 27, 4, 2, 108, 444, 26, 81, 116]
BASE_URL = 'http://en.wikipedia.org'
def main(word):
""" Query wikipedia until you hit the philosophy page
Phrase must be a non-empty string
"""
if not word:
word = raw_input('First word that comes to mind: ')
url_path = _format_phrase_for_wikipedia(word)
phrase = _query_wikipedia_loop(url_path)
print "\n\n{0} NYC\n".format(phrase)
def _query_wikipedia_loop(url_path):
""" Helper to run the queries"""
print "checking page: {0}".format(url_path)
full_url = BASE_URL + url_path
resp = requests.get(full_url)
if not resp.ok:
logging.error("sorry, broke on link: {0}".format(url_path))
return None
link, output = _get_link_or_output(resp.content)
if output:
return output
else:
return _query_wikipedia_loop(link)
def _get_link_or_output(content):
""" Find the first link in the body of text of a wikipedia page
"""
soup = BeautifulSoup(content)
page_body = soup.body.find(id="mw-content-text")
first_link, content = get_first_link_and_page_content(page_body)
# if we made it to one of the "attractor" pages, parse the entry for the
# "linked list" string
title = soup.body.h1.span.text
if title == "Greek language":
output = _get_linked_list_from_string(content.text, indices_greek)
return None, output
return first_link, None
def get_first_link_and_page_content(page_body):
""" Returns the first link in the body of text. You should pass in the
#mw-content-text div from the wikipedia page
"""
# search the paragraphs in order for the first link
for content in page_body.findAll('p'):
# sometimes the first link is bad, we only want ones that are
# wikipedia pages i.e. start with "/wiki/"
first_link = _search_links_for_first_nice_link(content.findAll('a'))
if first_link:
return first_link, content
# sometimes it's a "list" page, with no links in the paragraphs
for list_item in page_body.findAll('li'):
first_link = _search_links_for_first_nice_link(list_item.findAll('a'))
if first_link:
break
return first_link, content
def _search_links_for_first_nice_link(links):
""" look through the list of links for the first one that is in the normal
wikipedia format
"""
# shuffle them for fun, and it's no longer an attractor
#import random
#random.shuffle(links)
for link in links:
href = link.get('href') or ''
if href.startswith('/wiki/'):
logging.debug('href starts with /wiki/')
first_link = link.get('href')
return first_link
return None
def _get_linked_list_from_string(string, indices):
""" Get the phrase "linked list" from the string
"""
logging.debug("pulling linked list from: " + string)
return "".join(string[i] for i in indices)
def _format_phrase_for_wikipedia(phrase):
""" Capitalize every word and replace spaces with underscores, the way that
wikipedia urls are formatted
"""
formatted = '_'.join(a[0].upper() + a[1:] for a in phrase.split(' ')
if len(a) > 0)
return "/wiki/{0}".format(formatted)
if __name__ == "__main__":
word = sys.argv[1] if len(sys.argv) > 1 else None
main(word)
; 'LinkedList NYC' printed out using a Linked List implementation in ASM
;
; Elliott Carlson - x@sublim.nl
extern malloc
extern free
extern putchar
%macro init 1
mov dword [%1], 0
%endmacro
; Append mactro to add one or more passed items to the linked list procedure
%macro append 1-*
%rep %0
push dword %1
push linkedlist
call ll_append
%rotate 1
%endrep
%endmacro
; Print out the linked list
%macro print 1
push dword [%1]
call ll_print
%endmacro
; Cleanup the linked lists allocated memory
%macro cleanup 1
push dword [%1]
call ll_cleanup
%endmacro
section .data
size_i:
struc node
info: resd 1
next: resd 1
endstruc
len: equ $ - size_i
section .bss
linkedlist: resd 1
section .text
global main
; Main
main:
; Save the stack
push ebp
mov ebp, esp
; Initialize list as empty
init linkedlist
; Append the hex codes of the message 'LinkedList NYC' to
; the linked list via the append macro
append 0x4c, 0x69, 0x6e, 0x6b, 0x65, 0x64, 0x4c
append 0x69, 0x73, 0x74, 0x20, 0x4e, 0x59, 0x43
; Print out the contents of the linked list
print linkedlist
; Clean up allocated memory
cleanup linkedlist
; Restore stack
mov esp, ebp
pop ebp
ret
; Linked list append
; Add an element to the linked list
ll_append:
; Save the stack
push ebp
mov ebp, esp
; Save registers
push eax
push ebx
; Get the allocated memory of the linked list - push to eax
push len
call malloc
mov ebx, [ebp + 12]
mov [eax + info], ebx
mov dword [eax + next], 0
; Check if the linked list is currently null
mov ebx, [ebp + 8]
cmp dword [ebx], 0
je ll_append_null
mov ebx, [ebx]
ll_append_next:
; Find the address of the last element in the linked list
cmp dword [ebx + next], 0
je ll_append_last
mov ebx, [ebx + next]
jmp ll_append_next
ll_append_last:
; Set the pointer to the address of the last element
mov [ebx + next], eax
jmp ll_append_exit
ll_append_null:
; Set pointer to first element
mov [ebx], eax
ll_append_exit:
; Restore registers
pop ebx
pop eax
; Restore stack
mov esp, ebp
pop ebp
ret 8
; Linked list print
; Print all elements out from a linked list
ll_print:
; Save the stack
push ebp
mov ebp, esp
; Save register
push ebx
; Get the address of the first element in the list
mov ebx, [ebp + 8]
; If ebx is 0, then the list is empty - bothing to print
cmp ebx, 0
je ll_print_exit
ll_print_next:
; Loop through the linked list and print each character
push dword [ebx + info]
call putchar
mov ebx, [ebx + next]
; As long as ebx doesn't equal 0 (end of list) then loop
cmp ebx, 0
jne ll_print_next
; Print a new line character at the end
push dword 10
call putchar
ll_print_exit:
; Restore stack
pop ebx
mov esp, ebp
pop ebp
ret 4
; Linked list cleanup
; Deallocate memory used by the linked list
ll_cleanup:
; Save stack
push ebp
mov ebp, esp
; Save register
push eax
; Get address of the current position of the stack in the linked list
mov eax, [ebp + 8]
; Check if we have passed the end of the linked list
cmp eax, 0
je ll_cleanup_exit
; Go to the next available address in the linked list and loop
push dword [eax + next]
call ll_cleanup
; Set the address of the current element and free it from memory
push eax
call free
add esp, 4
ll_cleanup_exit:
; Restore register
pop eax
; Restore stack
mov esp, ebp
pop ebp
ret 4
local response = http.request {
url = 'http://www.linkedlistnyc.org'
}
s = response.content
lk = string.match(s, "<title>(.*)</title>")
local twilio = require('webscriptio/lib/twilio.lua')
local ACCOUNTSID = '<YOUR TWILIO ACCOUNT SID>'
local AUTHTOKEN = '<YOUR TWILIO AUTH TOKEN>'
local response = twilio.sms(
ACCOUNTSID,
AUTHTOKEN,
'<YOUR TWILIO NUMBER>',
request.form.phonenumber,
lk
)
if response.statuscode == 201 then
return 'Text message sent. '..lk..'\n'
else
return 'An error occurred. Check the phone number you used.'
end
import java.util.Scanner;
public class IceCreamGame {
/**
* @author Hannah Chen
* hannahelainechen@gmail.com
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] questions = {
"4C in decimal? " ,
"Number of US Senators plus how many pints of ice cream I might get? " ,
"Number of stories of each of the towers of the former WTC in New York? " ,
"Section number of Copyright Law regarding Fair Use? " ,
"HTTP status code indicating server acknowledging request to switch protocol? " ,
"Number of days of summer divided by 5. You know, that movie with that Zooey girl. " ,
"Street number of Amsterdam Ale House? " ,
"How many years of solitude? Add five to that. " ,
"Atomic number of element used to make zombies in Call of Duty?" ,
"Number of years that the Hundred Years' War lasted? " ,
"Number of teeth of a full set of adult teeth? " ,
"Number of cards that make up a typical tarot deck? " ,
"TI calculator that made high school math so easy... " ,
"Prefix code to block caller ID for a prank call? " };
String a = "LinkedList NYC";
System.out.println("Test your useless trivia! Answer some questions!");
System.out.println("Oh, and if you get any wrong you have to start over...");
boolean end = false;
while(!end) {
for (int i = 0; i < a.length(); i++) {
System.out.println(questions[i]);
if (input.nextInt() == (int)a.charAt(i) ) {
if (i == a.length() - 1) {
System.out.println(a);
end = true;
break;
}
continue;
}
else {
System.out.println("Start over.");
break;
}
}
}
}
}
import java.util.*;
import java.util.concurrent.Callable;
public class AcronyMiser {
/* Remove all non-uppercase characters from s.
*
* This is the algorithm for which we want to find the best List implementation!
*/
private static void acronymize(List<Character> s) {
Iterator<Character> i = s.iterator();
while(i.hasNext()) {
if (!Character.isUpperCase(i.next()))
i.remove();
}
}
private static final int N = 100000; // number of runs per List implementation
public static void main(String[] args) throws Exception {
// the string to acronymize:
final List<Character> s = asList(args[0]);
// Callables for each List implementation, which return a new copy of the string when called:
Callable<List<Character>>[] constructors = new Callable[] {
new Callable<List<Character>>() {
public List<Character> call() {
return new ArrayList<Character>(s);
}
},
new Callable<List<Character>>() {
public List<Character> call() {
return new LinkedList<Character>(s);
}
},
new Callable<List<Character>>() {
public List<Character> call() {
return new Vector<Character>(s);
}
},
new Callable<List<Character>>() {
public List<Character> call() {
List<Character> stack = new Stack<Character>();
stack.addAll(s);
return stack;
}
},
};
// try each implementation N times, outputting stats to stderr, and keep track of the best:
long bestTime = Long.MAX_VALUE;
List<Character> bestList = null;
for (Callable<List<Character>> constructor : constructors) {
List<Character> list = constructor.call();
System.err.println("=" + className(list) + "=");
long t = System.nanoTime();
for (int i = 0; i < N; i++) {
list = constructor.call();
acronymize(list);
}
t = System.nanoTime() - t;
System.err.println((t / N) + "ns");
if (t < bestTime) {
bestTime = t;
bestList = list;
}
}
// we have our winning List implementation!
// print its name and value to stdout:
System.out.println(className(bestList) + " " + asString(bestList));
}
//
// utility methods //
//
private static List<Character> asList(String s) {
// there are easier ways to do this, but not without referencing a particular List implementation,
// and i wanted to avoid picking favorites :'(
char[] chars = s.toCharArray();
Character[] characters = new Character[chars.length];
for (int i = 0; i < chars.length; i++)
characters[i] = chars[i];
return Arrays.asList(characters);
}
private static String asString(List<Character> characters) {
StringBuilder s = new StringBuilder();
for (Character c : characters)
s.append(c);
return s.toString();
}
private static String className(Object o) {
String name = o.getClass().getName();
return name.substring(name.lastIndexOf('.') + 1);
}
}
$(->
linkMeBabyOneMoreTime()
)
pixel_map = [
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,1,0,0,0,1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[0,1,0,1,0,1,0,0,1,0,1,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,1,0,0,1,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,1,0,0,0,1,0,0,0,1,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
]
linkMeBabyOneMoreTime = ->
# set some size variables
xScale = pixel_map[0].length
yScale = pixel_map.length
bigger = if xScale >= yScale then xScale else yScale
pixel_size = Math.ceil(100 / bigger) # round up to get some overlap
delay = 75 # for animation
# add the divs
for y in [0...yScale]
for x in [0...xScale]
$('body').append "<div class='offscreen' style='left: #{x * pixel_size}%; top: #{y * pixel_size}%; width: #{pixel_size}%; height: #{pixel_size}%;' />" if pixel_map[y][x] == 1
# remove the offscreen class to trigger the animation
$('div').each (i)->
setTimeout(=>
$(this).removeClass('offscreen')
, i * delay)
# show my credit
setTimeout(->
$('footer').fadeIn('slow')
, ($('div').length + 3) * delay)
import mechanize
import urlnorm
import urllib2
import re
import sys
VALID_CHARS = '^([-A-Za-z0-9+&@#/%=~_()| ]*)$'
def validate_search_term(search_term):
return bool(re.search(VALID_CHARS, search_term))
def print_url(url, letter_index, max_index):
if (not url or letter_index == -1):
print ''
else:
padding = ' ' * (max_index - letter_index)
print '%s%s %s %s' % (padding, url[0:letter_index], url[letter_index], url[letter_index+1:])
def find_matching_links(br, target_word, result, visited):
if (not target_word):
return result
else:
current_URL = urlnorm.norm(br.geturl())
current_letter = target_word[0].lower()
if (current_letter.isspace()):
return find_matching_links(br, target_word[1:], result + [('', -1, ' ')], visited)
else:
matching_index = current_URL[7:].find(current_letter)
if (matching_index == -1):
return []
else:
new_result = result + [(current_URL, matching_index + 7, current_letter)]
links = list(br.links())
for link in links:
try:
link_URL = urlnorm.norm(link.absolute_url)
if (link_URL not in visited):
br.open(link_URL)
new_visited = visited.copy()
new_visited.add(link_URL)
# print "visiting: " + urlnorm.norm(br.geturl())
new_visited.add(urlnorm.norm(br.geturl()))
child_result = find_matching_links(br, target_word[1:], new_result, new_visited)
if (child_result):
return child_result
except Exception, e:
continue
return []
def main():
if (len(sys.argv) < 3 ):
print "usage: python ll-print.py <url> <search term>"
print "example: python ll-print.py http://www.hunch.com 'hunch team'"
exit(0)
root_URL = sys.argv[1]
search_term = sys.argv[2]
if (not validate_search_term(search_term)):
print "Invalid search term. Please only use valid url characters and spaces."
exit(1)
first_letter = search_term[0]
first_letter_match = root_URL.find(first_letter.lower())
if (first_letter_match != -1):
try:
br = mechanize.Browser()
br._factory.is_html = True
result = []
br.open(root_URL)
# print "visiting: " + urlnorm.norm(br.geturl())
visited = set([urlnorm.norm(br.geturl()), urlnorm.norm(root_URL)])
result = find_matching_links(br, search_term, result, visited)
if (result):
max_index = max(result, key=lambda u: u[1])[1]
for l, i, c in result:
print_url(l, i, max_index)
except urlnorm.InvalidUrl:
print "Invalid root URL"
except urllib2.URLError, e:
print "Error opening root URL"
print e
except Exception, e:
print e
finally:
exit(1)
if __name__ == "__main__":
main()
(ns secd.linkedlistnyc
(:use [secd.core])
(:gen-class))
(defn -main []
(do
(do-secd* [:nil :dum
:ldf [:ld [0 0] :null
:sel
[:join]
[:ld [0 0] :car :writec
:nil :ld [0 0] :cdr :cons
:ld [1 0] :ap :join]
:rtn]
:cons
:ldf [:nil
:ldc [76 105 110 107 101 100
76 105 115 116
32
78 89 67
10]
:cons
:ld [0 0] :ap :rtn]
:rap])
nil))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment