Skip to content

Instantly share code, notes, and snippets.

@davidallsopp
davidallsopp / typed_eq.py
Last active December 29, 2015 10:19
A slightly typesafe (!) comparison function in Python. Only a runtime check of course, but will fail fast with a clear exception rather than silently comparing different types than can never be equal. I'm sure this is wildly unpythonic, but given that I've seen bugs from this kind of comparison even in statically typed languages like Java and Sc…
def eq(first, *rest):
for r in rest:
assert type(first) is type(r), "Different types %s, %s for inputs (%s,%s)" % (type(first), type(r), first, r)
if first != r:
return False
return True
# eq(1) - True
# eq(1, 1) - True
# eq(1, 1, 1) - True
@davidallsopp
davidallsopp / lola.txt
Created January 17, 2014 09:33
Some useful git log aliases. Put into ~/.gitconfig in the [alias] section
lol = log --graph --decorate --pretty=oneline --abbrev-commit
lola = log --graph --decorate --pretty=oneline --abbrev-commit --all
lolan = log --graph --decorate --pretty=oneline --abbrev-commit --all --show-notes
@davidallsopp
davidallsopp / random
Last active January 3, 2016 13:59
Generating secure passwords
head -c 32 /dev/random | base64
# e.g.
# Xv1FnaWlNmMJxs2UYGawn24h4+ueyigZQJEN43hcF44=
# Can also trim the trailing '=' by using head again
# and use echo so we get a newline:
echo $(head -c 32 /dev/random | base64 | head -c 32)
@davidallsopp
davidallsopp / Tails.java
Created January 22, 2014 13:41
A generic Java method for taking the tails (progressively shorter sublists) of a List. Does not include the empty list (unlike the Haskell tails function), though this is trivially changed.
import java.util.*;
public class Tails {
/** Not including the empty list */
public static <A> List<List<A>> tails(List<A> xs) {
ArrayList<List<A>> tails = new ArrayList<List<A>>(xs.size());
for (int i = 0; i < xs.size(); i++) {
ArrayList<A> tail = new ArrayList<A>(xs.size() - i);
tails.add(tail);
@davidallsopp
davidallsopp / ThreadException.java
Created February 17, 2014 13:55
Handling otherwise-unhandled exceptions in a thread. See the javadoc for Thread.setUncaughtExceptionHandler(): "Set the handler invoked when this thread abruptly terminates due to an uncaught exception. A thread can take full control of how it responds to uncaught exceptions by having its uncaught exception handler explicitly set. If no such han…
Thread t = new Thread() {
public void run() {
// do something useful
}
};
t.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
public void uncaughtException(Thread exThread, Throwable ex) {
// handle it here
}
@davidallsopp
davidallsopp / Subseqs.scala
Last active August 29, 2015 13:57
Lazily generate all subsequences of an Iterator or Iterable, up to the specified length, returning a new Iterator.
import scala.collection.mutable.ListBuffer
// See also http://stackoverflow.com/questions/22633598/creating-an-iterator-of-subsequences-from-an-iterator-of-items/
/** Lazily generate all subsequences of an Iterator or Iterable, up to the specified length, returning a new Iterator. */
class Subseqs[A](n: Int)(i: Iterator[A]) extends Iterator[List[A]] {
val buffer = new ListBuffer[A]()
//buffer ++= i.take(n) // NO - inconsistent behaviour of take() with iterators
// see http://stackoverflow.com/questions/7619642/consume-items-from-a-scala-iterator
(1 to n).foreach(_ => buffer += i.next())
@davidallsopp
davidallsopp / Timer.scala
Created March 27, 2014 11:42
Little utility for timing a block of code
object Timer {
/** Time a block of code, print the duration in millis, and return the value of the block*/
def time[A](f: => A): A = time2(f) match {
case (a, nanos) =>
println("time: " + nanos / 1000000L + "ms")
a
}
/** Time a block of code, return a tuple of the value of the block and the duration in nanos */
implicit class Crossable[X](xs: Traversable[X]) {
def cross[Y](ys: Traversable[Y]) = for { x <- xs; y <- ys } yield (x, y)
}
@davidallsopp
davidallsopp / ComposePartial.scala
Last active August 29, 2015 13:59
Composing partial functions such that isDefinedAt works end-to-end. Requires that the functions are pure. Adapted from https://groups.google.com/forum/#!topic/scala-user/fnw_367xTTw
val f = Map("a" -> 1, "b" -> 2) //> f : scala.collection.immutable.Map[String,Int] = Map(a -> 1, b -> 2)
val g = Map(1 -> 'c', 3 -> 'd') //> g : scala.collection.immutable.Map[Int,Char] = Map(1 -> c, 3 -> d)
//def pandThen[A, B, C](pf1: PartialFunction[A, B], pf2: PartialFunction[B, C]): PartialFunction[A, C] = {
// Function.unlift((a: A) => pf1.lift(a) flatMap pf2.lift)
//}
implicit class ComposePartial[B, C](pf: PartialFunction[B, C]) {
def andThenPartial[D](that: PartialFunction[C, D]): PartialFunction[B, D] =
Function.unlift(pf.lift(_) flatMap that.lift)
@davidallsopp
davidallsopp / fizzbuzz.hs
Last active December 25, 2015 20:49
Fizzbuzz one-liners in Haskell, following on from jbrains and srbaker (https://gist.github.com/jbrains/2a29465457bddcca0c45)
-- Using pattern match - adapted from http://rosettacode.org/wiki/FizzBuzz#Scala
-- (Naturally, this can be formatted sensibly rather than as a gratuitous one-liner!)
fizzbuzz :: Integer -> String
fizzbuzz n=case map(mod n)[3,5]of[0,0]->"FizzBuzz";[0,_]->"Fizz";[_,0]->"Buzz";_->show n
-- The canonical version at http://rosettacode.org/wiki/FizzBuzz#Haskell using guards
-- can be packed into an even shorter one-liner: