Skip to content

Instantly share code, notes, and snippets.

View stefanoc's full-sized avatar

Stefano Cobianchi stefanoc

View GitHub Profile
@stefanoc
stefanoc / query.sql
Last active June 21, 2016 11:37
Window function example
truncate table events;
CREATE TABLE events(ref_id integer, event_type text, ts integer);
INSERT INTO events (ref_id, event_type, ts) VALUES (1, 'foo', 1), (1, 'bar', 1), (2, 'foo', 0), (3, 'foo', 0), (1, 'foo', 4), (3, 'foo', 7), (2, 'bar', 10);
select
ref_id,
event_type,
ts,
first_value(ts) over (
partition by ref_id, event_type order by ts asc rows between 1 following and unbounded following
@stefanoc
stefanoc / list.rb
Created December 21, 2015 15:39
List
class List
attr_accessor :head, :tail
def initialize(head, tail)
self.head = head
self.tail = tail
freeze
end
def prepend(elem)
class Option
private def initialize(value)
@value = value
end
def self.Some(value)
new(value)
end
None = new(nil)
@stefanoc
stefanoc / xss_sanitizer.b
Created August 25, 2015 12:38
XSS sanitizer
module XssSanitizer
extend ActiveSupport::Concern
class Scrubber < Loofah::Scrubber
ALLOWED_TAGS = %w(
strong span em b u i a
h1 h2 h3
div p ul ol li blockquote br
)
@stefanoc
stefanoc / tis100.rs
Created August 21, 2015 22:31
tis-100
#![allow(dead_code)]
use std::thread;
use std::sync::mpsc::{sync_channel, SyncSender, Receiver};
use std::collections::HashMap;
struct Port {
rx: Receiver<i32>,
tx: SyncSender<i32>
}
@stefanoc
stefanoc / dice.rb
Last active August 29, 2015 14:15
Dadi
require 'pp'
dice = [0, 0, 1, 2, 3, 4]
throws = dice.product(dice, dice, dice, dice)
counts = throws.inject(Hash.new(0)) { |t, p| t[p.inject(&:+)] += 1; t }
pp counts.map { |(k, v)| [k, (v.fdiv(throws.length) * 100).round(3)] }
@stefanoc
stefanoc / computed_attributes.rb
Created February 17, 2015 21:55
Computed attributes
module ComputedAttributes
module ClassMethods
def compute(name, components, &block)
getter = -> do
value = instance_variable_get("@_#{name}")
unless value
value = instance_exec(&block)
instance_variable_set("@_#{name}", value)
end
value
@stefanoc
stefanoc / Cargo.toml
Created February 5, 2015 20:14
Rust word counter
[package]
name = "wc"
version = "0.0.1"
authors = ["stefano"]
[dependencies]
regex = "0.1.12"
regex_macros = "0.1.6"
@stefanoc
stefanoc / promise.rb
Created December 3, 2014 09:53
Promises
class Promise
class << self
alias :make :new
end
def initialize(block)
@result = []
@thread = Thread.new(@result) do |result|
result[0] = block.call
end
@stefanoc
stefanoc / test.rb
Created October 29, 2014 15:16
Word freqs
require 'pp'
dict = Hash.new(0)
File.open(ARGV[0], 'r') do |src|
while line = src.gets
line.strip.scan(/\w+/) { |word| dict[word] += 1 }
end
end
pp dict