Skip to content

Instantly share code, notes, and snippets.

@rklemme
rklemme / ListFileTestThreaded2.java
Created January 27, 2013 12:53
comp.lang.java: enumerating the first n files in a directory with many, many files.
package file;
import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
@rklemme
rklemme / FinalTest.java
Created January 7, 2013 21:57
How Java fakes closures.
package lambda;
public class FinalTest {
public static Runnable create(final int limit) {
return new Runnable() {
@Override
public void run() {
for (int i = 0; i < limit; ++i) {
@rklemme
rklemme / Enum_n_min_1.rb
Created November 30, 2012 11:51
Obtain the smalles n items from an Enumerable
module Enumerable
def n_min(n)
raise "Illegal argument: #{n.inspect}" unless n > 0
mins = []
each do |item|
mins.push item
mins.sort!
mins.pop if mins.size > n
@rklemme
rklemme / periodic-notify.sh
Created November 27, 2012 15:22
Periodically write something to stdin of a console command
#!/usr/bin/bash
# create fifo and ensure cleanup on exit
fifo=fifo-$$
mkfifo "$fifo"
trap 'rm "$fifo"' 0
# other command
cat -n <"$fifo" &
bg=$!
@rklemme
rklemme / diff-sorted.rb
Created October 24, 2012 08:24
Diff two sorted files
#!/bin/ruby
def trace(old, new)
printf "%p old=%p new=%p\n", caller[0], old, new
end
def fetch(io)
s = io.gets and s.chomp!
s
end
@rklemme
rklemme / read_msg_at_custom_delimiter.rb
Created August 20, 2012 09:35
Example of reading messages with a custom delimiter other than \n.
require 'socket'
DELIMITER = "\x04".freeze
server = TCPServer.new '127.0.0.1', 5556
printf "Server at port %p\n", server.addr
loop do
Thread.new(server.accept) do |client|
printf "Client %p START\n", client
@rklemme
rklemme / method-wrap.rb
Created June 27, 2012 09:18
Wrap all methods with a specific code
class Foo
def self.method_added(m)
t = Thread.current
unless t[:_hook]
t[:_hook] = true
begin
alias_method "_#{m}", m
@rklemme
rklemme / grid.rb
Created June 18, 2012 06:41
Grid example
class Grid
def initialize(dim_x, dim_y)
@x = dim_x
@y = dim_y
@store = {}
end
def [](coord)
@store[validate_coord coord]
HTML_TAG_REPLACEMENTS = {
'br' => "\n",
}
HTML_QUOTE_REPLACEMENTS = {
'quot' => '"',
'amp' => '&',
}
def strip_html(str, tag = HTML_TAG_REPLACEMENTS, quot = HTML_QUOTE_REPLACEMENTS)
str.gsub %r{
@rklemme
rklemme / BitSet.rb
Last active October 5, 2015 07:58
Basis for a bit set which uses String as storage. Storage is split up into multiple String instances to avoid too large allocations.
#!/usr/bin/ruby
# Implementation of a bit set which stores membershio in binary
# Strings managed in chunks.
class BitSet
ZERO = "\000".encode(Encoding::BINARY).freeze
DEFAULT_SEGMENT_SIZE = 1024 * 1024
# Create the BitSet instance. If max_num is given, we preallocate
# as much memory as needed.