Skip to content

Instantly share code, notes, and snippets.

@guyarad
guyarad / slots_pickling_mixin.py
Last active August 4, 2019 12:39
Enable pickling on Python classes that uses __slots__
class SlotsPicklingMixin(object):
# otherwise, subclasses will still have `__dict__`
__slots__ = ()
def __init__(self):
assert hasattr(self, '__slots__')
def __getstate__(self):
all_slots = itertools.chain.from_iterable(
getattr(t, '__slots__', ()) for t in type(self).__mro__)
@guyarad
guyarad / Tidy JSON.py
Last active September 14, 2016 14:23
Text filter intended to be used with TextWrangler application (Mac OSX) in order to reformat (tidy-up) a JSON file.
#!/usr/bin/python
#
# Script was modified from:
# https://steveswinsburg.wordpress.com/2014/09/26/textwrangler-filters-to-tidy-xml-and-tidy-json/
# Modified by Guy Arad, and can be found in:
# https://gist.github.com/guyarad/d80b9d5652a6616e1c3138b6a86310c4
#
# Installation:
# Copy to "~/Library/Application Support/TextWrangler/Text Filters"
#
import wrapt
import functools
def for_all_methods(decorator):
"""
CLASS DECORATOR.
Based on http://stackoverflow.com/a/6307868/916568
When applied to a class, will automatically decorate all public
methods (ones that don't start with an underscore) using the
given ``decorator``.
@guyarad
guyarad / classic_enum_wrapper_for_sa.py
Created October 5, 2016 20:04
Wrapper for Python classic enum to be used as SQL Alchemy enum type
# DEFINITION
# ==========
class PythonEnumWrapper(sa.Enum):
def __init__(self, cls):
"""
Initializes a new ``PythonEnumWrapper`` to be used as ``sqlalchemy.Enum``
Args:
cls: a classic enumeration type
"""
@guyarad
guyarad / lazy_logging.py
Last active November 11, 2016 12:11
Lazy Logging - the below snippet is relevant when you wish to log some debugging information, but that information is relatively costly to generate. Ideally, you'll want to generate that information only when DEBUG level is actually enabled. In other words, only when the message formatting actually occurs.
# IMPLEMENTATION
class LazyLogging(object):
"""
A utility class that wraps a method
"""
def __init__(self, function):
self.function = function
def __str__(self):
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("log")
def simple():
if logger.isEnabledFor(logging.DEBUG):
logger.debug('Stupid log message ' + ' '.join([str(i) for i in range(20)]))
@guyarad
guyarad / timing.py
Created February 8, 2017 06:23
Timing context manager
@contextmanager
def timing(label=None, time_func=simulator.timestamp):
"""
Can be used in conjunction with ``with`` statement to easily measure duration.
Args:
time_func:
label: represents the measurement
Returns:
A callable. Once invoked will return one of the following (duration in seconds):
@guyarad
guyarad / pycharm-intellisense-issues.py
Last active July 30, 2019 13:23
PyCharm issuing wrong and annoying intellisense warnings (Python 2.7.14, PyCharm 2017.3.2)
# Python 2.7.14, PyCharm 2017.3.2
from collections import defaultdict
some_default_dict = defaultdict(list)
some_default_dict[1] = 'a'
some_default_dict[2] = 'b'
some_objects = [{'id': i} for i in range(10)]
obj_by_id = {obj['id']: obj for obj in some_objects}
@guyarad
guyarad / mongodb_collection_sizes.js
Last active December 29, 2019 23:06 — forked from joeyAghion/mongodb_collection_sizes.js
List mongodb collections in descending order of size. Helpful for finding largest collections. First number is "size," second is "storageSize."
function getReadableFileSizeString(fileSizeInBytes, decimalPlacer=1) {
// for more concise solutions see: https://stackoverflow.com/questions/10420352/converting-file-size-in-bytes-to-human-readable-string
var i = 0;
var scale = 1024;
var byteUnits = [' B', ' KiB', ' MiB', ' GiB', ' TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
while (fileSizeInBytes >= scale) {
fileSizeInBytes = fileSizeInBytes / scale;
i++;
}
@guyarad
guyarad / build.sh
Created November 26, 2019 07:28 — forked from lucasea777/build.sh
Python C Extension Hello World
gcc -fpic --shared $(python3-config --includes) greetmodule.c -o greet.abi3.so
# can also use $(pkg-config --cflags python-3.5)
# or
# python3 setup.py install --record files.txt --user