Thursday, November 1, 2012

Code Samples

This examines the custom styles used for github gists embedded in blog posts.

Python

from twisted.internet import defer, reactor, task
from twisted.web.client import getPage
maxRun = 2
urls = [
'http://twistedmatrix.com',
'http://yahoo.com',
'http://www.google.com',
]
def pageCallback(result):
print len(result)
return result
def doWork():
for url in urls:
d = getPage(url)
d.addCallback(pageCallback)
yield d
def finish(ign):
reactor.stop()
def test():
deferreds = []
coop = task.Cooperator()
work = doWork()
for i in xrange(maxRun):
d = coop.coiterate(work)
deferreds.append(d)
dl = defer.DeferredList(deferreds)
dl.addCallback(finish)
test()
reactor.run()
Lisp

(defun my-echo-server ()
(format t "Starting server.~%")
(as:tcp-server nil 9003 ; nil is "0.0.0.0"
(lambda (socket data)
;; echo the data back into the socket
(as:write-socket-data socket data))
(lambda (err) (format t "listener event: ~a~%" err)))
;; catch sigint
(as:signal-handler 2 (lambda (sig)
(declare (ignore sig))
(as:exit-event-loop))))
(as:start-event-loop #'my-echo-server)
Scheme (Chicken)


Clojure

(defn read-agent-error-handler [agnt, exception]
(println "Whoops! " agnt " had a problem: " exception))
(def read-agent
(agent
"zero bytes"
:validator string?
:error-handler read-agent-error-handler))
(defn big-read [old-value seconds]
"Pretent to read a really big file"
(time (Thread/sleep (* seconds 1000)))
"<contents of big file>")
(defn read-watch [key agnt old-value new-value]
(println "File has been read!")
(println (str "New file data is: " new-value))
(println ""))
(add-watch read-agent "reader-01" read-watch)
view raw 05-agent.clj hosted with ❤ by GitHub
(defn relay [x i]
(when (:next x)
(send (:next x) relay i))
(when (and (zero? i) (:report-queue x))
(.put (:report-queue x) i))
x)
(defn run [action-count agent-count]
(let [q (new java.util.concurrent.SynchronousQueue)
hd (reduce (fn [next _] (agent {:next next}))
(agent {:report-queue q})
(range (dec action-count)))]
(doseq [i (reverse (range agent-count))]
(send hd relay i))
(.take q)))

No comments:

Post a Comment