🎭 Jester gist stars for garybernhardt
A♦
types.markdown975 stars

# This document has moved!

It's now [here](https://www.destroyallsoftware.com/compendium/types/baf6b67369843fa2), in The Programmer's Compendium.
The content is the same as before, but being part of the compendium means that it's actively maintained.
A♦
K♣
gistfile1.md87 stars

# Things that programmers don't know but should

(A book that I might eventually write!)

Gary Bernhardt

I imagine each of these chapters being about 2,000 words, making the whole book about the size of a small novel.
For comparison, articles in large papers like the New York Times average about 1,200 words.
Each topic gets whatever level of detail I can fit into that space.
For simple topics, that's a lot of space: I can probably walk through a very basic, but working, implementation of the IP protocol.
More subtle topics will get less detail: for RSA, maybe I'd (1) give a rough sketch of the number theory, (2) show that we can treat arbitrarily large byte arrays as numbers, and (3) say "combine them in the obvious way".
K♣
Q♥
gistfile1.txt78 stars

(Chapters marked with * are already written. This gets reorganized constantly
and 10 or so written chapters that I'm on the fence about aren't listed.)

Programmer Epistemology
  * Dispersed Cost vs. Reduced Cost
  * Verificationist Fallacy
  * Mistake Metastasis
  The Overton Window
  Epicycles All The Way Down
  The Hyperspace Gates Were Just There
Software Design
  * Structured Design: Understanding Graphs
Q♥
J♠
selectable_queue.rb24 stars

A queue that you can pass to IO.select.

# A queue that you can pass to IO.select.
#
# NOT THREAD SAFE: Only one thread should write; only one thread should read.
#
# Purpose:
#   Allow easy integration of data-producing threads into event loops.  The
#   queue will be readable from select's perspective as long as there are
#   objects in the queue.
#
# Implementation:
#   The queue maintains a pipe. The pipe contains a number of bytes equal to
#   the queue size.
J♠
十♦
gistfile1.sh19 stars

# Has your OS/FS/disk lost your data?

# cd to the directory containing your project repositories and run the command
# below. (It's long; make sure you get it all.) It finds all of your git repos
# and runs paranoid fscks in them to check their integrity.

(set -e && find . -type d -and -iname '.git' | while read p; do (cd "$(dirname "$p")" && (set -x && git fsck --full --strict)); done) && echo "OK"

# I have 81 git repos in my ~/proj directory and had no errors.

# You might get messages about dangling commits, dangling blobs, etc. Those
# aren't errors. If it prints "OK" at the end, your repos are all valid.
十♦
9♣
1-description.txt17 stars

This tool is used to compare microbenchmarks across two versions of code. It's
paranoid about nulling out timing error, so the numbers should be meaningful.
It runs the benchmarks many times, scaling the iterations up if the benchmark
is extremely short, and it nulls out its own timing overhead while doing so. It
reports results graphically with a text interface in the terminal.

You first run it with --record, which generates a JSON dotfile with runtimes
for each of your benchmarks. Then you change the code and run again with
--compare, which re-runs and generates comparison plots between your recorded
and current times. In the example output, I did a --record on the master
branch, then switched to my scoring_redesign and did a --compare. In my output,
three of the benchmarks' runtimes look to be unchanged; the other three got
9♣
8♥
inline.rb12 stars

#!/usr/bin/env ruby

require 'base64'
require 'nokogiri'
require 'uri'

def main
  html = Nokogiri::HTML($stdin.read)
  inline_all_images(html)
  inline_all_css(html)
  $stdout.write(html.to_s)
end
8♥
7♠
build.rb10 stars

require "erb"
require "pathname"

DOT_TEMPLATE=<<-END
digraph {
size="20,20";
overlap=false;
sep=0.4;
graph [fontname=Helvetica,fontsize=10];
node [fontname=Helvetica,fontsize=10];
edge [fontname=Helvetica,fontsize=10];
rankdir=TB;
7♠
6♦
rebuild9 stars

#!/usr/bin/env bash

set -e

if [ -e static ]; then
    rm -r static
fi
mkdir -p static
sass src/sass/main.scss > static/application.css
$(npm bin)/browserify src/js/main.js > static/application.js
cp -r src/html/* static
6♦
5♣
gistfile1.rb8 stars

# Goal: put a non-Rails-aware Ruby library using normal `require`s in
# lib/sim. Have it transparently reloaded between requests like Rails app
# code is.
#
# The code here goes inside of your configure block in
# config/environments/development.rb. There are two parts, commented inline.

# Reload code whenever the simulator changes.
config.watchable_dirs["lib/sim"] = [:rb]
config.watchable_files << "lib/sim.rb"

# Manually unload and reload the simulator before every request. This assumes
5♣
4♥
gistfile1.txt8 stars

Turning The Design Clock Back

Object-oriented design principles haven't had the effect we hoped for. The
SOLID principles are excellent design guidelines, but experience shows that
programmers find them difficult to follow. What do we do about this?
Surprisingly, the Structured Design literature of forty years ago contains
compelling solutions to many current design problems. They're simple and easy
to understand, but were lost in the noise as OO rose to popularity. We'll
reinterpret these simple design ideas in a modern context, finding that many of
our most promising new design ideas resemble them. Rapid web application
development, the area of professional programming in most dire need of design
improvements, will serve as an example.
4♥
3♠
gistfile1.rb7 stars

# I don't really see any services here. What I see is:
#   - Normal HTTP boundary stuff (params flash, redirect).
#   - Model creation and retrieval.
#   - Warden manipulation, which is an odd done but smells like boundary.
#
# I left all of the HTTP boundary stuff in the controller (and only the
# controller). I moved the model creation/retrieval into simple class methods
# in the models. I moved the warden manipulation stuff into
# ApplicationController (with caveats that I'll discuss inline).
#
# Commentary on each class follows:
3♠
2♦
cron.rake5 stars

task :cron => :environment do
  DatabaseBackup.back_up_to_s3!
end
2♦
A♦
gistfile1.sh5 stars

find $(manpath | tr ':' '\n') -iname '*.1' | xargs cat | (LC_CTYPE=C tr -C '[:alnum:]-_' '\n') | egrep '^--[\-_[:alnum:]]+$' | sort | uniq -c | sort -n
A♦
K♣
wrap.rb3 stars

Probably a really bad implementation of word wrapping

class Wrap
  def self.wrap(s, max_length)
    raise ArgumentError.new("Maximum wrap length can't be 0") if max_length == 0
    return [""] if s.rstrip.empty?

    # Split into words and whitespace blocks
    blocks = s.split /(\s+|\S+)\b/

    lines = []
    line = ""

    until blocks.empty?
K♣
Q♥
gistfile1.c3 stars

An excerpt from GCC's reload.c

static int
find_reusable_reload (rtx *p_in, rtx out, enum reg_class rclass,
		      enum reload_type type, int opnum, int dont_share)
{
  rtx in = *p_in;
  int i;
  /* We can't merge two reloads if the output of either one is
     earlyclobbered.  */

  if (earlyclobber_operand_p (out))
    return n_reloads;
Q♥
J♠
gistfile1.diff3 stars

diff --git a/app/views/devise/shared/_links.erb b/app/views/devise/shared/_links.erb
dissimilarity index 99%
index 414904b..0b0b21d 100644
--- a/app/views/devise/shared/_links.erb
+++ b/app/views/devise/shared/_links.erb
@@ -1,19 +1,15 @@
-<%- if controller_name != 'sessions' %>
-  <%= link_to "Sign in", new_session_path(resource_name) %><br />
-<% end -%>
-
-<%- if devise_mapping.registerable? && controller_name != 'registrations' %>
-  <%= link_to "Sign up", new_registration_path(resource_name) %><br />
J♠
十♦
1-shell-session.sh3 stars

find ~/Downloads/Gmail -type f | grep -v '\.git' | ruby -rdate -e 'today = Date.today; STDIN.each { |path| content = File.read(path.strip); begin; from = content.grep(/^From:/).fetch(0); date = content.grep(/^Date:/).fetch(0); puts from if Date.parse(date) > today - 365; rescue IndexError; end }' | while read line; do echo "$line" | ~/.mutt/add-aliases.sh; done
十♦
9♣
run-tests.sh3 stars

#!/usr/bin/env bash

main() {
    if [ ! -p .test-commands ]; then
        mkfifo .test-commands
    fi

    while true; do
        cmd=$(cat .test-commands)
        if [[ $cmd == "" ]]; then
            continue
        else
9♣
8♥
gistfile1.txt2 stars

set conf_name to text returned of ¬
	(display dialog ¬
		"Enter conference name:" with title ¬
		"Schedule Conference" default answer ¬
		"" default button 2)

tell application "OmniFocus"
	tell default document
		set newProject to make new project with properties {name:conf_name}
		
		tell project conf_name
			make new task with properties {name:"Schedule " & conf_name & " in calendar"}
8♥
7♠
gistfile1.sh2 stars

(set -e && ls content/*.markdown | while read p; do DATE=$(echo $p | cut -d '/' -f 2 | cut -d '-' -f 1-3); TARGET=$(echo $p | sed 's/-/\//' | sed 's/-/\//' | sed -E 's/[0-9]+-//' | perl -pe 's/^(.*\/.*\/.*\/)(.)(.*)$/\1\u\2\3/' | sed -E 's/-|_/ /g'); echo $TARGET; mkdir -p $(dirname $TARGET); echo "<\!-- $DATE -->" > $TARGET; cat $p >> $TARGET; rm $p; done)
7♠
6♦
gistfile1.txt1 stars

using the git reflog

# I have a repo with two commits
failbowl:temp(master) grb$ git shortlog
Gary Bernhardt (2):
      commit 1
      commit 2

# I destroy the second commit
failbowl:temp(master) grb$ git reset --hard HEAD^
HEAD is now at 7454aa7 commit 1


# It's gone
6♦
5♣
gistfile1.lua1 stars

x = function()
    y = function()
        local table = 5
    end
    local old_table = table
    y()
    assert(table == old_table and table ~= 5)
end
x()
5♣
4♥
gistfile1.txt1 stars

#!/bin/bash

set -e

if [ $# -gt 0 ]; then # we have args
    filename=$1
    (set +e; grep -r 'spec_helper' $filename) > /dev/null
    if [ $? -eq 1 ]; then # no match; we have a stand-alone spec
        standalone_spec=1
    fi
else # we have no args
    filename='spec'
4♥
3♠
gistfile1.txt1 stars

It's a subscription-based screencast site, where I post a new five- to
ten-minute screencast every week. For this, people pay a nominal fee
around $3 per month, giving them access to the full archives and new
screencasts as they happen. The style would be similar to the
screencasts I've posted on my blog: just me and the computer, recorded
in one take, although with much practicing. I'd focus not on new
languages and tools, but on the minute-to-minute mechanics of
effective programming practices, with an obvious bias toward the stack
and practices that I use.
3♠
2♦
gistfile1.txt1 stars

Date: Thu, 3 Oct 2013 17:16:51 -0700
From: Gary Bernhardt <gary.bernhardt@gmail.com>
To: info@wdsearch.com
Subject: Mailing practices

I suspect that you guys know this, but just in case: your emailing
practices have been resulting in... less than good impressions among the
people you aim to recruit. Here are some tweets, none of which were
written by me:

Ugh, Nicholas Meyler. Scummiest Scumbag Recruiter ever.
- https://twitter.com/ryanbigg/status/385918215559184384
2♦
A♦
inbox_diff.sh1 stars

inbox_blobs() {
  git ls-tree -r master | grep 'INBOX' | awk '{print $3}' | sort
}

diff <(cd ../Gmail && inbox_blobs) <(inbox_blobs) | grep '<\|>' | while read marker hash; do
  echo "$marker $(git show $hash | grep -m 1 '^Subject:')"
done | sort
A♦
K♣
gistfile1.txt1 stars

bench "paths", :without_gc => true, :gc_time => true do
  PATHS[0, 1000].each { |choice| Score.score(choice, "x" * 16) }
end

Output:

...!.!.!.!..............................................
filtering paths
  Before: |                       --X-----------------------                     |
  After:  |                                   ---------X-------------------------|
          0                                                                   14.1
K♣
Q♥
gistfile1.txt1 stars

failbowl:selecta(scoring_redesign) $ ruby ../readygo/readygo.rb --compare benchmark.rb
.!.!.!.!.!.!.!.!..!.!.!.!.!.!.!.!.!.!...!.!.!.!.!.!.!.!.............................................................................................................

filtering non-matching
  Baseline: |                                                      X-----------|
  Current:  |                                X---------                        |
            0                                                           6.848 ms

filtering matching exactly
  Baseline: |                                              X-------------------|
  Current:  | X                                                                |
            0                                                          68.219 ms
Q♥
J♠
gistfile1.rb1 stars

module RenderToHTML
  def self.book
    [title, css, body].join("\n")
  end

  private

  def self.title
    commit_hash = `git log -1 --pretty="format:%H"`
    %{
      <div class="title">
        <h1>#{TITLE}</h1>
J♠
十♦
gistfile1.ml1 stars

open Parser;;
open Stringutil;;

type t = String of string | List of t list

let rec of_module m =
  List (String "module" :: of_definitions m)

and of_definitions ds =
  List.map of_definition ds

and of_definition (FuncDef func_def) =
十♦
9♣
test.rb1 stars

# This is a stripped-down example based on Selecta's TTY handling. We store the
# TTY state in `tty_state`, then go into an infinite loop. When the loop is
# terminated by a ^C, we try to restore the TTY state. It's important that this
# work, but it doesn't in some subtle situations, and I don't know why.
#
# Save this file as test.rb and run it via this command, where `stty` should
# successfully restore the TTY state:
#   bash -c 'echo | ruby test.rb'
#
# Next, run it via this command, where `stty` should fail to restore the TTY
# state:
#   bash -c 'echo $(echo | ruby test.rb)'
9♣
8♥
twitter_lib.rb1 stars

module TwitterLib
  def self.authenticate
    libs = [Twitter, TweetStream]
    libs.each do |lib|
      lib.configure do |config|
        config.consumer_key = ENV.fetch("TWITTER_CONSUMER_KEY")
        config.consumer_secret = ENV.fetch("TWITTER_CONSUMER_SECRET")
        config.oauth_token = ENV.fetch("TWITTER_OAUTH_TOKEN")
        config.oauth_token_secret = ENV.fetch("TWITTER_OAUTH_SECRET")
      end
    end
  end
8♥
7♠
test.rb1 stars

#!/usr/bin/env ruby

# This script tests par2 recovery when the par2 files themselves are corrupted.
# Process:
#   1. Generate a file containing all 256 possible bytes.
#      (More would be better, but it gets slow fast.)
#   2. Generate par2 data for the file.
#   3. Individually corrupt each par2 file at each offset.
#      (Write byte 0 unless the offset already contains byte 0; then, write byte 255.)
#      (Writing each possible byte would be better, but it gets slow fast.)
#   4. After each corruption, verify the par2 data, then reverse the corruption.
#   5. Produce a summary of what the par2 verification commands' output, along with the frequencies of each output string.
7♠
6♦
gistfile1.txt1 stars

Automatically fix rubocop errors, with one commit per error

rubocop | egrep ' (W|C): ' | cut -d ' ' -f 3 | sort -u | sed 's/:$//' | while read cop; do
    git checkout .
    rubocop -a --only "$cop"; 
    if [[ $(git diff --stat) != '' ]]; then
        git add --all
        git commit -m "fix rubocop cop $cop"
    fi
done
6♦
5♣
fancy_tab_completion.vim0 stars

" Remap the tab key to do snippets, autocompletion or indentation depending on
" the context (cobbled together by Gary Bernhardt; partly based on
" http://www.vim.org/tips/tip.php?tip_id=102)
"
" Because this uses the private 'Jumper' function in snippetsEmu, you'll need
" to edit '/.vim/plugin/snippetsEmu.vim' to make it public. To do that, just
" replace all occurrences of '<SID>Jumper' with just 'Jumper'. There were only
" two occurrences in my copy.
" 
" The g:snippetsEmu_key variable must be defined, but not to a function key.
" (I have no idea why function keys break it.) "  I recommend something on the
" leader prefix that you don't use.
5♣
4♥
gistfile1.py0 stars

class BowlingScorer:
    def __init__(self, rolls):
        rolls = rolls[:]
        self.score = sum(self.score_frame(rolls) for _ in range(10))

    def score_frame(self, rolls_left):
        roll1 = rolls_left.pop(0)
        if roll1 == 10:
            return 10 + rolls_left[0] + rolls_left[1]

        roll2 = rolls_left.pop(0)
        if roll1 + roll2 == 10:
4♥
3♠
gistfile1.py0 stars

def santa(people):
    return dict(zip(people, reversed(people)))


def describe_santa():
    bob, george, judy = 'bob jones', 'george jetson', 'judy smith'

    def takes_lists_of_people():
        santa([bob, george])

    def pairs_people_with_eachother():
        pairs = santa([bob, george])
3♠
2♦
gistfile1.txt0 stars

# Loop through git revisions, counting lines of Python
# code, unit test code, cucumber code, and media. The
# paths and filenames are specific to my project; if
# you want to use this, you'll have to change them.

reverse() {
  sed 'x;1!H;$!d;x'
}
(echo 'rev,python code,unit test,cucumber,media' &&
git rev-list HEAD |
reverse |
while read rev; do
2♦
A♦
gistfile1.diff0 stars

diff --git a/tests/test_entity.py b/tests/test_entity.py
index c3c4aec..8410b9d 100644
--- a/tests/test_entity.py
+++ b/tests/test_entity.py
@@ -209,6 +209,15 @@ class TestMatchesDict(unittest.TestCase):
             creator=['Matt', 'Nobody'],
             tags=['fun', 'boring']) == self.e
 
+    #def test_order_independence_of_query(self):
+    #    assert not self.e.matches_dict(creator=['Matt'],
+    #                                   title=['DO NOT MATCH'])
+    #    assert not self.e.matches_dict(creator=['DO NOT MATCH'],
A♦
K♣
gistfile1.htm0 stars

The Limits of TDD
#date 2009-11-09 21:47
#tags python,tdd

<p>
    My <a href="/2009/11/how_i_started_tdd.html">last post</a> about TDD
    generated some great responses, some of which were skeptical. A few common
    complaints about TDD were brought up, and posed with civility, so I'd like
    to address them.
</p>

<h4>Complaint: You weren't stupid enough</h4>
K♣
Q♥
gistfile1.txt0 stars

failbowl:repo grb$ cloc .
    1472 text files.
    1061 unique files.                                          
     883 files ignored.

http://cloc.sourceforge.net v 1.06  T=36.0 s (11.3 files/s, 1457.1 lines/s)
--------------------------------------------------------------------------------
Language           files     blank   comment      code    scale   3rd gen. equiv
--------------------------------------------------------------------------------
HTML                 196       818        14     30174 x   1.90 =       57330.60
Python               169      4155      1517     13664 x   4.20 =       57388.80
CSS                   13       120         8       749 x   1.00 =         749.00
Q♥
J♠
gistfile1.py0 stars

def live_cell_count(x, y):
    square_coords = [(x-1, y-1),
                     (x+0, y-1),
                     (x+1, y-1),
                     (x-1, y+0),
                     (x+1, y+0),
                     (x-1, y+1),
                     (x+0, y+1),
                     (x+1, y+1)]

    count = sum(1 for x, y in square_coords
                if cell_alive_exists(x, y))
J♠
十♦
gistfile1.py0 stars

How would you rather write your tests?

# How would you rather write your tests?
# Tell it to @garybernhardt (or gary.bernhardt@gmail.com)

# 1) Hypothetical RSpec-inspired Python library (PSpec?) that does violence to nature
with describe('my class'):
    with it('adds numbers'):
        sum = MyClass.add(1, 1)
        sum.should == 2

# Actually, I think the only acceptable name for the above library would be "withit"

# 2) Mote (minimal violence to nature) + Expecter Gadget (violence free)
十♦
9♣
gistfile1.txt0 stars

# One extra keyword needed for an RSpec clone. Just sayin.
describe('integers') do:
    it('can be added') do:
        expect(1 + 1) == 2
    it('can be subtracted') do:
        expect(2 - 1) == 1
    it('truncates on division') do:
        expect(3 / 2) == 1

# Implement blocks with plain old generators:
def describe(description):
    ... set stuff up
9♣
8♥
gistfile1.sh0 stars

ls _posts/* | grep -v '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]' | while read fn; do day=`grep '#postdate\|#date' $fn | cut -d '-' -f 3 | cut -d ' ' -f 1`; git mv $fn `echo $fn | sed "s/-\([0-9][0-9]\)-/-\1-$day-/"`; done
8♥
7♠
gistfile1.txt0 stars


failbowl:temp $ rm -rf env && pip install -E env dingus && ls -l env/lib/python2.6/site-packages
Creating new virtualenv environment in env
  New python executable in env/bin/python
  Installing setuptools...done.....
Downloading/unpacking dingus
  Downloading dingus-0.2.tar.gz
  Running setup.py egg_info for package dingus
Installing collected packages: dingus
  Running setup.py install for dingus
    warning: build_py: byte-compiling is disabled, skipping.
    warning: install_lib: byte-compiling is disabled, skipping.
7♠
6♦
gistfile1.txt0 stars

failbowl:temp $ rm -rf env && pip install -E env dingus && . env/bin/activate && pip update pip 
Creating new virtualenv environment in env
  New python executable in env/bin/python
  Installing setuptools...done.....
Downloading/unpacking dingus
  Downloading dingus-0.2.tar.gz
  Running setup.py egg_info for package dingus
Installing collected packages: dingus
  Running setup.py install for dingus
    warning: build_py: byte-compiling is disabled, skipping.
    warning: install_lib: byte-compiling is disabled, skipping.
Successfully installed dingus
6♦
5♣
gistfile1.txt0 stars

failbowl:temp $ deactivate; rm -rf env && pip install -E env dingus && . env/bin/activate && ls -l env/lib/python2.6/site-packages                        
zsh: command not found: deactivate
Creating new virtualenv environment in env
  New python executable in env/bin/python
  Installing setuptools...done.....
    Complete output from command /Users/grb/temp/env/bin/python /Users/grb/temp/env/bin/easy_install /opt/local/Library/Frameworks/...ar.gz:
    Processing pip-0.7.2.tar.gz
Running pip-0.7.2/setup.py -q bdist_egg --dist-dir /var/folders/Vr/Vrnubf6zGE4qOl6GIOQjh++++TI/-Tmp-/easy_install-AFWiid/pip-0.7.2/egg-dist-tmp-72Ag6W
warning: no files found matching '*.html' under directory 'docs'
warning: no previously-included files matching '*.txt' found under directory 'docs/_build'
no previously-included directories found matching 'docs/_build/_sources'
warning: build_py: byte-compiling is disabled, skipping.
5♣
4♥
gistfile1.txt0 stars

failbowl:temp $ pip install -U pip
Downloading/unpacking pip
  Downloading pip-0.7.2.tar.gz (68Kb): 68Kb downloaded
  Running setup.py egg_info for package pip
    warning: no files found matching '*.html' under directory 'docs'
    warning: no previously-included files matching '*.txt' found under directory 'docs/_build'
    no previously-included directories found matching 'docs/_build/_sources'
Installing collected packages: pip
  Found existing installation: pip 0.7.2
    Uninstalling pip:
Exception:
Traceback (most recent call last):
4♥
3♠
gistfile1.sh0 stars

whodoneit: Find who introduced a certain pattern to the code base

# Originally from Jonathan Penn, with modifications by Gary Bernhardt
function whodoneit() {
    (set -e &&
        for x in $(git grep -I --name-only $1); do
            git blame -f -- $x | grep $1;
        done
    )
}
3♠
2♦
gistfile1.txt0 stars

# This doesn't work – it calls nil.join (the map seems to return nil?)
puts things.to_a.sort_by(&:id).map do |thing|
  "#{thing.id} #{thing.url}"
end.join("\n")

# This DOES work (the only difference is that the map uses curlies instead of do/end).
puts things.to_a.sort_by(&:id).map { |thing|
  "#{thing.id} #{thing.url}"
}.join("\n")
2♦
A♦
gistfile1.lua0 stars

function wrap(f)
    return function()
        -- Storing the result of the wrapped function is the source of the
        -- problem.
        result = f()
        return result
    end
end

function f()
    return 1, 2
end
A♦
K♣
gistfile1.sh0 stars

# Setting up the graph; you can skip to the next comment.
$ hg init
$ echo 0 > 0
$ hg ci -Am 0
adding 0
$ echo 1 > 1
$ hg ci -Am 1
adding 1
$ hg co 0
0 files updated, 0 files merged, 1 files removed, 0 files unresolved
$ echo 2 > 2
$ hg ci -Am 2
K♣
Q♥
gistfile1.rb0 stars

# Braintree has a cutesy search query API:
class Sweeper
  def self.sweep!
    Braintree::Subscription.search do |s|
      s.status.is Braintree::Subscription::Status::Canceled
    end
  end
end

# Putting expectations on it sucks, but less than I expected:
describe Sweeper do
  it 'searches for canceled subscriptions' do
Q♥
J♠
gistfile1.txt0 stars

failbowl:destroyallsoftware.com(76m|braintree!?) $ cat Gemfile                                              
source 'http://rubygems.org'

gem 'rails', '3.0.3'

# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'

gem 'sqlite3-ruby', :require => 'sqlite3'

gem 'braintree', '2.7.0'
gem 'devise', '1.1.5'
J♠
十♦
gistfile1.txt0 stars

# I do this:

module ActiveRecord
  class Base
    @@old_save = instance_method(:save)

    def save *args
      @@old_save.bind(self).call *args
    end
  end
end
十♦
9♣
gistfile1.scpt0 stars

set conf_name to text returned of ¬
	(display dialog ¬
		"Enter conference name:" with title ¬
		"Schedule Conference" default answer ¬
		"" default button 2)

tell application "Things"
	set newProject to make new project ¬
		with properties {name:conf_name}
end tell

tell application "Things"
9♣
8♥
gistfile1.txt0 stars

Disregard this. I'm not a competent programmer.
8♥
7♠
gistfile1.sass0 stars

$grid_column_width: 40px
$grid_column_margin: 10px
$grid_columns: 12
$grid_width: $grid_columns * ($grid_column_width + $grid_column_margin * 2)

=container
  margin-left: auto
  margin-right: auto
  width: $grid_width
	
=alpha
  margin-left: 0
7♠
6♦
gistfile1.rb0 stars

module Rack
  module Utils
    def parse_nested_query(qs, d = nil)
      params = ActiveSupport::OrderedHash.new

      (qs || '').split(d ? /[#{d}] */n : DEFAULT_SEP).each do |p|
        k, v = unescape(p).split('=', 2)
        normalize_params(params, k, v)
      end

      return params
    end
6♦
5♣
model_spec.rb0 stars

  # mock-based (interaction)
  # db independent, but tied to implementation (I can change the AR call without affecting the behavior and this will fail)
  context "data gathering" do
    it "finds all indicators associated with the given sector and includes indicators not associated with any sectors" do
      sector = stub_model(Sector, :id => 6)

      Indicator.should_receive(:where).with("sector_id is null or sector_id = ?", sector.id)

      Indicator.for_sector(sector)
    end
  end
5♣
4♥
gistfile1.txt0 stars

CantTouchThis = Class.new do
  def to_s
    '<CantTouchThis>'
  end
end.new

class Stripper
  def self.strip(klass)
    klass.class_eval do
      Stripper::constants_to_remove.each do |c|
        self.const_set c.to_sym, CantTouchThis
      end
4♥
3♠
group_steps.rb0 stars

Given /^I'm subscribed as a group host for ([^ ]*) users?$/ do |users|
  users = users.to_i
  steps %Q{
    Given I'm on the account page
    Given I enter valid billing details
  }
  choose("for_many") # THIS FAILS
  fill_in "people ($9 per month each)", :with => users
  steps('And I press "Subscribe"')
end
3♠
2♦
after.rb0 stars

Before/after let comparison

  class Delegator
    takes :request, :route_path, :resource, :delegate_name

    let(:delegate_method) { @resource.record_class.method(method_name) }
    let(:method_name) { @delegate_name.split('.').last.to_sym }

    def delegate
      delegate_method.call(*delegate_args)
    end

    def delegate_args
      inference_sources = InferenceSources.new(@request,
2♦
A♦
lightning.txt0 stars

PyCodeConf 2011 Lightning Talk Signup

I want to give a lightning talk about: 

"Wat?"

I need the projector: yes / no

Yes
A♦
K♣
gistfile1.rb0 stars

require 'download_policy'

describe DownloadPolicy do
  let(:screencast) { stub(:free? => false) }
  let(:anonymous_user) { nil }
  let(:user_with_access) { stub(:has_screencast_access? => true) }
  let(:user_without_access) { stub(:has_screencast_access? => false) }

  it "is disallowed for anonymous users" do
    subject.allow_download_for?(screencast, anonymous_user).should be_false
  end
K♣
Q♥
gistfile1.rb0 stars

# Make a user that we'll add a book to.
user = User.create!
controller.stub(:current_user) { user }

# This prints []. The book list is empty.
p user.books

# Expect a book to be added to the user. This fails (see below)
expect {
  post :create, :id => asin
}.to change { user.books }.from([]).to([book])
Q♥
J♠
gistfile1.txt0 stars

Python array methods:

>>> [m for m in dir([]) if not m.startswith("_")]
['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse',
'sort']

Ruby array methods:

>> ([].methods - Object.methods).sort
=> ["&", "*", "+", "-", "<<", "[]", "[]=", "all?", "any?", "assoc", "at",
"choice", "clear", "collect", "collect!", "combination", "compact", "compact!",
"concat", "count", "cycle", "delete", "delete_at", "delete_if", "detect",
J♠
十♦
gistfile1.rb0 stars

# Rails controller
def create
  @profile = ProfileManager.create(params[:profile])
rescue ProfileManager::CreationFailed => e
  render :new, :errors => e.errors
end

# Raptor route
create :to => "ProfileManager#create", ProfileManager::CreationFailed => render(:new)
十♦
9♣
gistfile1.rb0 stars

# Hash form:
{
  :current_user => "CurrentUser.current_user"
}

# Discovery form with inverted app structure:
module Injectables
  def current_user(session)
    User.find(:id => session['current_user_id'])
  end
end
9♣
8♥
gistfile1.txt0 stars

Last login: Mon Jan 30 16:54:38 on ttys000
failbowl:~(master!?) $ rvm install ree
Installing Ruby Enterprise Edition from source to: /Users/grb/.rvm/rubies/ree-1.8.7-2011.12
ree-1.8.7-2011.12 - #fetching (ruby-enterprise-1.8.7-2011.12)
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 7773k  100 7773k    0     0  2447k      0  0:00:03  0:00:03 --:--:-- 2513k
ree-1.8.7-2011.12 - #extracting ruby-enterprise-1.8.7-2011.12 to /Users/grb/.rvm/src/ree-1.8.7-2011.12
Applying patch 'tcmalloc' (located at /Users/grb/.rvm/patches/ree/1.8.7/tcmalloc.patch)
Applying patch 'stdout-rouge-fix' (located at /Users/grb/.rvm/patches/ree/1.8.7/stdout-rouge-fix.patch)
Applying patch 'no_sslv2' (located at /Users/grb/.rvm/patches/ree/1.8.7/no_sslv2.diff)
Applying patch 'lib64' (located at /Users/grb/.rvm/patches/ree/lib64.patch)
8♥
7♠
gistfile1.rb0 stars

#!/bin/ruby

guard 'spork' do
  watch(%r{^config/.*\.rb$})
  watch(%r{^config/environments/.*\.rb$})
  watch(%r{^config/initializers/.*\.rb$})
  watch(%r{^features/support/.*\.rb$})
  watch('spec/spec_helper.rb')
end
7♠
6♦
gistfile1.txt0 stars

failbowl:temp(master+!?) $ git st
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#	modified:   a
#	new file:   c
#
# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
6♦
5♣
gistfile1.rb0 stars

describe 'a' do
  it "raises an error when no source is found for an argument" do
    klass = Class.new { def f(unknown_argument); end }
    expect do
      injector.call(klass.new.method(:f))
    end.to raise_error(Syringe::UnknownInjectable)
end
end
5♣
4♥
gistfile1.txt0 stars

I asked Comcast to stop leaving me two four-second voice mails every day. This is their response.

Dear Gary,

Thank you for contacting Comcast Email Support. My name is Jean and I
appreciate your time and effort in contacting us. I hope you are having
a great day.

I understand that you would like us to put your name and your number,
xxx-xxx-xxxx, right at this moment. I truly understand how this must
have been frustrating to you and I do apologize for any inconvenience
this has caused you. I can certainly understand how important it is for
you to have this resolved as soon as possible in order for you to not
receive any call. Rest assured that we, at Comcast, are dedicated to
4♥
3♠
gistfile1.rb0 stars

def tweet(o)
  match(o) {
    with(o.name == "garybernhardt") { raise TrollError }
    with(Image i) { tweet ShortLink.for_image(i) }
    with(Text t) { actually_tweet_here }
  }
end
3♠
2♦
changes.rb0 stars

class Changes < Actor
  out :timeline_tweets_out
  takes :tweets_in, :friends_in

  def before
    @friends = @friends_in.pop
  end

  def pump
    tweet = @tweets_in.pop
    timeline_tweets_out << tweet if @friends.include_user?(tweet.user)
  end
2♦
A♦
gistfile1.txt0 stars

Isolation, Data & Dependencies

Isolated unit testing—mocking everything—is a controversial topic. We'll briefly review what it is today, why people like it, and its problems. Then, on to the real goal: a trip through behavior vs. data, mutation vs. immutability, how data shape affords parallelism, transforming interface dependencies into data dependencies, and what it might look like to unify all of these with a slightly tweaked version of OO. Fortunately, Ruby is sufficiently flexible that we can do the whole experiment without leaving it.
A♦
K♣
gistfile1.txt0 stars

A Whole New World

Few of us have participated in the creation of our
infrastructure—operating systems, compilers, terminals, editors, etc.,
even though many of us know how to build them in theory. Collectively,
we suffer from a learned helplessness around them: to build new
high-level tools, we'd also have to rebuild some of the
infrastructure, sometimes going all the way down to the kernel. We
can't imagine triggering such a large cultural and technological
shift, so we don't even try to build truly new tools for ourselves.
I've been working on such a stack-busting tool and, though I won't
spill the beans on it here, I'll say that it's required me to
K♣
Q♥
gistfile1.txt0 stars

#define assert_equals(expected, actual)\
    if (expected != actual) {\
        printf("FAIL: %#Lx != %#Lx\n", (uint64_t)expected, (uint64_t)actual);\
        exit(1); \
    }

#define run_test(name)\
    printf("%s\n", #name);\
    name();
Q♥
J♠
gistfile1.applescript0 stars

tell application "Finder"
  open file ((path to home folder as text) & "Dropbox:notes") using ((path to applications folder as text) & "MacVim.app")
end tell

tell application "MacVim"
	activate
end tell
J♠
十♦
gistfile1.txt0 stars

failbowl:~(master!?) $ # Curl with normal user agent; get the correct text back
failbowl:~(master!?) $ curl -s 'https://gist.github.com/raw/4534954/b508396cb255b52a0defbc75c92e69ad5c2937b5/gistfile1.rb' | head -1
# I don't really see any services here. What I see is:

failbowl:~(master!?) $ # Curl as iPhone; get broken text back
failbowl:~(master!?) $ curl -s -A 'Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16' 'https://gist.github.com/raw/4534954/b508396cb255b52a0defbc75c92e69ad5c2937b5/gistfile1.rb' | head -1
# I don&#39;t really see any services here. What I see is:
十♦
9♣
gistfile1.txt0 stars

failbowl:~(master) $ irb
>> X = 1
=> 1
>> undef_const :X
NoMethodError: undefined method `undef_const' for main:Object
  from (irb):2
>> const_undef :X
NoMethodError: undefined method `const_undef' for main:Object
	from (irb):3
>> const_delete :X
NoMethodError: undefined method `const_delete' for main:Object
	from (irb):4
9♣
8♥
gistfile1.txt0 stars

>> class Foo; attr_accessor :hello; end
>> f = Foo.new
>> f.hello = lambda { puts "why no self?" }
>> f.hello
=> #<Proc:0x0000000102b6e768@(irb):12>
8♥
7♠
gistfile1.diff0 stars

--- /Users/grb/.rvm/gems/ruby-1.9.3-p194@investments/gems/values-1.5.0/lib/values.rb	2013-06-17 19:28:23.000000000 -0700
+++ values.rb	2013-06-25 17:28:17.000000000 -0700
@@ -1,7 +1,7 @@
 class Value
   def self.new(*fields)
     Class.new do
-      attr_reader *fields
+      attr_reader :hash, *fields

       define_method(:initialize) do |*values|
         raise ArgumentError.new("wrong number of arguments, #{values.size} for #{fields.size}") if fields.size != values.size
@@ -10,6 +10,8 @@
7♠
6♦
gistfile1.txt0 stars

thelongpoll: Acquiring lock on /Users/grb/.thelongpoll
thelongpoll: - Got it
thelongpoll: Is the mail client running?
thelongpoll:         * ps aux
thelongpoll: - No
thelongpoll: Checking git status
thelongpoll:         * (cd /Users/grb/Downloads/Gmail && git status --short)
thelongpoll: - Clean
thelongpoll: Don't need to commit to git
thelongpoll: Starting sync
thelongpoll:         * offlineimap
OfflineIMAP 6.5.4
6♦
5♣
gistfile1.txt0 stars

John Carmack on shadow volumes...

I recieved this in email from John on May 23rd, 2000.

- Mark Kilgard


I solved this in a way that is so elegant you just won't believe it.  Here
is a description that I posted to a private mailing list:

----------------------------------------------------------
5♣
4♥
gistfile1.txt0 stars

$ echo '#!/bin/ls /' > foo
$ ./foo
./foo

/:
bin  boot  dev	etc  home  initrd.img  lib  lib64  lost+found  media  mnt  opt	proc  root  run  sbin  selinux	srv  sys  tmp  usr  var  vmlinuz
$ echo '#!/bin/ls / /' > foo
$ ./foo
/bin/ls: cannot access / /: No such file or directory
4♥
3♠
gistfile1.txt0 stars

#!/bin/bash
/usr/bin/env ruby --disable-gems <(cat <<'EOF'
puts "ruby code goes here"
EOF)
3♠
2♦
gistfile1.txt0 stars

failbowl:~(master) $ cabal list --installed hunit
* HUnit
    Synopsis: A unit testing framework for Haskell
    Default available version: 1.2.5.2
    Installed versions: 1.2.5.2
    Homepage: http://hunit.sourceforge.net/
    License:  BSD3

failbowl:~(master) $ echo 'import HUnit' | runhaskell

/var/folders/g5/jl_jnwv57nn_rhnvd_v6wpqw0000gn/T/runghcXXXX79850.hs:1:8:
    Could not find module `HUnit'
2♦
A♦
gistfile1.txt0 stars

puts "export #{vars.map { |k, v| %{#{k}="#{v}"} }.join(" ")}"
A♦
K♣
gistfile1.txt0 stars

failbowl:rubies(master) $ git l
*   65cc7ef  (41 seconds)  <Gary Bernhardt>   (HEAD, master) Merge branch 'activate_command_cleanup'
|\
| * f4ced72  (2 minutes)   <Gary Bernhardt>   extract variables
| * f2760be  (3 minutes)   <Gary Bernhardt>   File.join instead of string interpolation
| * 94b8df5  (5 minutes)   <Gary Bernhardt>   activate command's imperative part is in activate!
|/
*   9291243  (7 minutes)   <Gary Bernhardt>   Merge branch 'ruby_info_cleanup'
|\
| * b7cb944  (9 minutes)   <Gary Bernhardt>   indentation
| * a3428c7  (10 minutes)  <Gary Bernhardt>   move RubyInfo field extraction into RubyInfo class
| * dff6a33  (15 minutes)  <Gary Bernhardt>   introduce ruby_info! command method
K♣
Q♥
gistfile1.rb0 stars

  it "requires an amount_charged greater than 0" do
    order = FactoryGirl.build(:order, :amount_charged => 0)
    order.valid?.should == false
    order.errors[:amount_charged].should == ["must be greater than 0"]
  end
Q♥
J♠
gistfile1.sh0 stars

git diff --name-status head~3000..head | grep '^D' | awk '{print $2}' | while read f; do git log -1 --pretty="format:%H" -- "$f"; done > temp.txt
J♠
十♦
gistfile1.txt0 stars

def adjust(t,h);(3*h)−(4*t*h);end
def adjust(t,h);(3*h)-(4*t*h);end
十♦
9♣
gistfile1.txt0 stars

CyBurTaz:	i programed my comps memory to read my 	own lang
RAVERgrl34:	LoL... oh muh god!
CyBurTaz:	FOXXY STFU
RAVERgrl34:	you are a piece of shit!
RAVERgrl34:	ROFL
RAVERgrl34:	LMAO
RAVERgrl34:	oh muh god!
RAVERgrl34:	you are lamest mother fucking i have ever 	seen!
RAVERgrl34:	oh muh god, you are lame.
9♣
8♥
gistfile1.txt0 stars

failbowl:~(master) $ curl 'http://maps.google.com/?saddr=St.%20Petersburg%20Shavrova%2015&daddr=St.%20Petersburg%20Sadovaya%2030&dirflg=r&output=json'
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
The document has moved
<A HREF="http://maps.google.com/maps?saddr=St.%20Petersburg%20Shavrova%2015&amp;daddr=St.%20Petersburg%20Sadovaya%2030&amp;dirflg=r&amp;output=json">here</A>.
</BODY></HTML>

failbowl:~(master) $ curl 'http://maps.google.com/maps?saddr=St.%20Petersburg%20Shavrova%2015&amp;daddr=St.%20Petersburg%20Sadovaya%2030&amp;dirflg=r&amp;output=json'
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
8♥
7♠
gistfile1.txt0 stars

$ heroku pg:backups
Installing Heroku Toolbelt v4... done.
For more information on Toolbelt v4: https://github.com/heroku/heroku-cli
Setting up node-v4.1.1... done
Installing core plugins heroku-cli-addons, heroku-apps, heroku-fork, heroku-git, heroku-local, heroku-run, heroku-status...
 ▸
Error reading plugin: heroku-apps. See /Users/grb/.heroku/error.log for more information.
Error reading plugin: heroku-cli-addons. See /Users/grb/.heroku/error.log for more information.
Error reading plugin: heroku-fork. See /Users/grb/.heroku/error.log for more information.
Error reading plugin: heroku-git. See /Users/grb/.heroku/error.log for more information.
Error reading plugin: heroku-local. See /Users/grb/.heroku/error.log for more information.
Error reading plugin: heroku-run. See /Users/grb/.heroku/error.log for more information.
7♠
6♦
user.py0 stars

from collections import namedtuple
from datetime import date

# Here's a user defined using the usual "OO" style.
class UserClass:
    def __init__(self, first, last, birthday):
        self.__first = first
        self.__last = last
        self.__birthday = birthday

    def name(self):
        return self.__first + " " + self.__last
6♦