Skip to content

Instantly share code, notes, and snippets.

View mkhl's full-sized avatar
🖤
…at any cost

Martin Kühl mkhl

🖤
…at any cost
View GitHub Profile
@mkhl
mkhl / permutations.swift
Last active December 9, 2015 20:37
Permutations of Sequences in Swift
func permutations<Sequence: SequenceType>(items: Sequence) -> [[Sequence.Generator.Element]] {
return items.reduce([[]]) { (perms, item) in
return perms.flatMap { perm in
return (0 ... perm.count).map { i in
var copy = perm
copy.insert(item, atIndex: i)
return copy
}
}
}
import PromiseKit
extension CollectionType {
func traverse<T>(transform: Generator.Element -> Promise<T>) -> Promise<[T]> {
return Promise { fulfill, reject in
var accumulator: [T] = []
var generator = self.generate()
func recurse() {
guard let next = generator.next() else {
fulfill(accumulator)
extension Dictionary {
mutating func merge(other: [Key: Value], by combine: (Value, Value) -> Value) {
for (key, newValue) in other {
if let oldValue = self[key] {
self[key] = combine(oldValue, newValue)
} else {
self[key] = newValue
}
}
}
extension CollectionType {
func indexBy<Key: Hashable>(keyFunction: (Generator.Element) -> Key) -> [Key: [Generator.Element]] {
var map: [Key: [Generator.Element]] = [:]
for element in self {
let key = keyFunction(element)
var elements = map[key] ?? []
elements.append(element)
map[key] = elements
}
return map
extension Array {
mutating func shuffle() {
if self.count < 2 { return }
for i in 0..<self.count {
let j = Int(arc4random_uniform(UInt32(self.count - i))) + i
if i != j {
swap(&self[i], &self[j])
}
}
}
Source: <http://enlivend.livejournal.com/36650.html>
@mkhl
mkhl / gist:1682605
Created January 26, 2012 12:42
Unix Exit Status Code Reference
0 # successful termination 64 # base value for error messages
64 # command line usage error
65 # data format error
66 # cannot open input
67 # addressee unknown
68 # host name unknown
69 # service unavailable
70 # internal software error
71 # system error (e.g., can't fork)
72 # critical OS file missing
@mkhl
mkhl / cdup.sh
Created December 13, 2011 22:19 — forked from ieure/cdup.sh
function cdup {
local dir=$PWD
local target=${*:-.git}
until [ -e "$dir/$target" -o "$dir" = "/" ]; do
dir="$(dirname "$dir")"
done
test -e "$dir/$target" && cd "$dir"
}
function catup {
walk "$@" |
sor 'file $file | grep -q Mach-O' |
sor 'otool -L $file | grep -q Cellar/readline/6.1'
@mkhl
mkhl / unicaps.py
Created June 3, 2011 22:25
Inspired by something Peter Hosey did. Converts text to small caps unicode glyphs.
#!/usr/bin/env python
import fileinput, unicodedata
def convert_char(char):
try:
name = unicodedata.name(char)
name = name.replace('LATIN SMALL LETTER', 'LATIN LETTER SMALL CAPITAL')
return unicodedata.lookup(name)
except KeyError: