Skip to content

Instantly share code, notes, and snippets.

View addam's full-sized avatar

Addam Dominec addam

View GitHub Profile
@addam
addam / timing.cpp
Created April 24, 2016 09:30
two-liner for measuring elapsed time in C++11
#include <chrono>
std::chrono::high_resolution_clock::time_point t_start = std::chrono::high_resolution_clock::now();
//...
float elapsedTime = std::chrono::duration_cast<std::chrono::duration<float>>(std::chrono::high_resolution_clock::now() - t_start).count();
@addam
addam / nonconst_call.cpp
Created May 25, 2016 10:04
Scott Meyers' suggestion to aviod const/nonconst method duplication
template<typename Result, typename M, typename A>
Result& nonconst_call(const M& m, A& argument)
{
return const_cast<Result&>(static_cast<const M&>(m)(argument));
}
Value const& Container::operator () (int index) const
{
return data[index];
}
@addam
addam / split_iterator.cpp
Last active May 25, 2016 10:04
Nearest neighbor search structure made simple. Performance is between sqrt(N) and N -- but fast enough for many purposes
template<typename T>
class SplitIterator
{
const float pivot;
typename vector<T>::const_iterator left, right, it;
const typename vector<T>::const_iterator begin, end;
public:
SplitIterator(const vector<T> &points, T origin) : pivot{origin.x()}, begin{points.begin()}, end{points.end()} {
assert (std::is_sorted(points.begin(), points.end(), [](T a, T b) { return a.x() < b.x(); });)
right = std::upper_bound(begin, end, origin, [](T a, T b) { return a.x() < b.x(); });
@addam
addam / inmerge.cpp
Last active May 25, 2016 10:07
function to copy-merge one sorted vector into another, in place
template<typename T>
void inmerge(std::vector<T> &target, const std::vector<T> &source)
{
target.resize(target.size() + source.size());
auto lit = target.crbegin() + source.size(), rit = source.rbegin();
auto lend = target.crend(), rend = source.rend();
auto out = target.rbegin();
while (rit != rend) {
*(out++) = (lit != lend and *rit < *lit) ? *(lit++) : *(rit++);
}
@addam
addam / pdf.py
Created June 7, 2016 15:18
minimalistic script that creates a PDF file
def format_dict(obj, refs=tuple()):
return "<< " + "".join("/{} {}\n".format(key, format_value(value, refs)) for (key, value) in obj.items()) + ">>"
def format_value(value, refs=tuple()):
if value in refs:
return "{} 0 R".format(refs.index(value) + 1)
elif type(value) is dict:
return format_dict(value, refs)
elif type(value) is list:
return "[ " + " ".join(format_value(item, refs) for item in value) + " ]"
@addam
addam / pairs.py
Created September 22, 2016 20:27
iterate over consecutive pairs
def pairs(seq, cyclic=True):
it = iter(seq)
first = prev = next(it)
for here in it:
yield prev, here
prev = here
if cyclic:
yield here, first
# I use this snippet in almost every script
# It is really simple but still I would prefer to import it from itertools if it was there...
@addam
addam / triangulate_polygon.py
Last active April 25, 2017 21:36
Delaunay-triangulate a simple polygon using Triangle
#!/usr/bin/python3
import triangle
from collections import OrderedDict
def triangulate(multipolygon):
vertices = OrderedDict()
indices = [[vertices.setdefault(co, len(vertices)) for co in poly] for poly in multipolygon]
dt = triangle.triangulate({"vertices": list(vertices), "segments": [s for f in indices for s in pairs(f)]}, "p")
segments = {s for poly in indices for s in pairs(poly)}
triangles = {tuple(tri) for tri in dt["triangles"]}
@addam
addam / setdefault.hpp
Last active May 19, 2017 07:28
setdefault for c++, the missing Python::dict method
/// setdefault(D, k, v) -> D.at(k), and set D[k]=v if k not in D
template<class T, class K, class V>
V& setdefault(T &map, const K &key, const V &default_value)
{
if (!map.count(key)) {
map.insert({key, default_value});
}
return map.at(key);
}
@addam
addam / pop.hpp
Created May 31, 2017 16:00
pop for c++ map/multimap, works like the Python::dict method
template<typename M>
M::mapped_type pop(M &m, M::const_iterator it)
{
assert (it != m.end());
M::mapped_type result = *it;
m.erase(it);
return result;
}
template<typename M>
@addam
addam / postgres_copy.py
Last active November 7, 2017 20:13
Copy data from a posgre SQL server to another using asyncpg
#!/usr/bin/python3
import asyncio
import asyncpg
from time import time
try:
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
except:
pass # it will just be slower, no harm done