Skip to content

Instantly share code, notes, and snippets.

@barsbek
barsbek / ordinality.sql
Created March 19, 2018 09:37
postgresql: add column with "id" from 1 with step 1
select * from some_table with ordinality as t(some_column, n)
@barsbek
barsbek / lateral.sql
Created March 19, 2018 14:16
postgresql: access preceding sub-selects in from clause
select * from t1, lateral (select * from t2 where t2.id = t1.id);
@barsbek
barsbek / frame_range.sql
Created March 19, 2018 17:17
postgresql: set frame's range in window function
select count(*) over(order by id rows between unbounded preceding and unbounded following); -- all rows in partition
select count(*) over(order by id rows between 2 preceding and 1 following); -- 2 rows before, current and next row
select count(*) over(order by id rows unbounded preceding); -- all rows before current
@barsbek
barsbek / crosstab.sql
Created March 20, 2018 06:45
postgresql: pivot table according to row_names, categories and values
select * from crosstab($$
select row_name, some_category, some_value --only 3 columns!
from some_table
$$, $$values(category1), (category2), ..., (categoryn)$$ -- same can be achieved by selecting distinct values
) as g(RowName type, Category1 type, Category2 type, ..., CategoryN type);
-- type of CategoryN should be the same as type of value
@barsbek
barsbek / include.rb
Created March 25, 2018 09:13
ruby: include class and instance methods from single module
module SomeModule
# instance methods:
def some_instance_method
# do something here
end
# module, which contains class methods
module ClassMethods
# class methods:
def some_class_method
@barsbek
barsbek / comparable.rb
Created March 25, 2018 09:24
ruby: create a comparable class
class Person
include Comparable
# Comparable adds methods, which allow to compare objects
attr_reader :age
def initialize(age)
@age = age
end
def <=>(another) # method is obligatory, as Comparable uses it to construct methods
@barsbek
barsbek / range.rb
Created March 25, 2018 09:52
ruby: range with custom class
class Ln
include Comparable
attr_reader :value
def initialize(n)
@current = n
@value = Math.log2(n)
end
# Objects of the range have to comparable
@barsbek
barsbek / zip.rb
Created March 26, 2018 07:27
ruby: group corresponding elements of arrays
[1,2,3].zip([5,6,7,9], [7]) #[[1, 5, 7], [2, 6, nil], [3, 7, nil]]
@barsbek
barsbek / lookaround.rb
Created March 26, 2018 08:23
ruby: regex lookaround
(?=foo) # followed by foo
(?<=foo) # preceded by foo
(?!foo) # is not followed by foo
(?<!foo) # is not preceded by foo
@barsbek
barsbek / gsub.rb
Created March 26, 2018 08:31
ruby: replace occurrence
"some string".gsub(pattern, replacement) # every occurrence of pattern is replaced by replacement
"other string".gsub(pattern) { |match| replacement } # every match is replaced by return value (replacement) of block
"hello".gsub(/./) { |c| "#{c.ord} " } # 104 101 108 108 111