Skip to content

Instantly share code, notes, and snippets.

@Susensio
Susensio / sd.fish
Created October 17, 2023 07:22 — forked from arcuru/sd.fish
Fish shell completions for ianthehenry/sd
# Completions for the custom Script Directory (sd) script
# MODIFIED from https://gist.github.com/patricksjackson/5065e4a9d8e825dafc7824112f17a5e6
# Improvements:
# - compliant with SD_ROOT
# - better handling of empty folders
# These are based on the contents of the Script Directory, so we're reading info from the files.
# The description is taken either from the first line of the file $cmd.help,
# or the first non-shebang comment in the $cmd file.
@Susensio
Susensio / cached_method.md
Last active April 11, 2024 08:59
Instance cached_method for unhashable self, type hinted, with optional parameters

Cached Method Decorator in Python

This repository provides a Python decorator @cached_method that caches method results similar to functools.lru_cache, but with each instance having its own cache.

Overview

The cached_method decorator allows you to cache the results of an instance method call so that subsequent calls with the same arguments will return the cached result instead of performing the computation again.

This decorator provides two key benefits:

  • The cache is cleared when the instance is garbage collected (by using weak references).
@Susensio
Susensio / pandas_groupby_mostfrequent.py
Created December 19, 2022 18:13
Pandas groupby and get most_frequent
# Default way of handling groupby and mostfrequent is slow
df.groupby(groupby_column)[null_column].agg(lambda x: x.iat[0])
# if there are nan's in df:
df.groupby(groupby_column)[null_column].agg(lambda x: x.iat[0] if not x.isnull().all() else np.nan)
# faster way: use value_counts and keep first value
(df
.groupby(groupby_column)[null_column]
.value_counts(sort=True, dropna=False)
@Susensio
Susensio / bash_xdg_compliant.sh
Last active February 22, 2023 08:17
Make bash follow XDG Base Directory specs. Must be run as root, it edits /etc files
#!/usr/bin/env bash
# Move ~/.bash* files to $XDG_CONFIG_HOME/bash/bash*
set -o nounset
set -o errexit
set -o pipefail
### ROOT SPACE
etc_bashrc_file="/etc/bash.bashrc"
etc_bashrcd_folder="/etc/bash/bashrc.d"
@Susensio
Susensio / DirRecursive.vba
Created February 3, 2022 10:38
Find paths in VBA with wilcard pattern in subdirectories, using DIR funcion
Public Function FindPathRecursive(StartFolder As String, Pattern As String, Optional SearchMode As VbFileAttribute = vbNormal) As String
' Función recursiva que permite buscar rutas con coincidencia de patrones, usando el widlcard comodín *
' Por ejemplo, permite buscar el archivo
' \\srvfs1\etiquetas\Bartender\Plantillas envase\UA_*\124755_*\L_Delantera.*
' con los parámetros
' StartFolder = "\\srvfs1\etiquetas\Bartender\Plantillas envase\"
' Pattern = "UA_*\124755_*\L_Delantera.*"
' devolviendo como resultado
' \\srvfs1\etiquetas\Bartender\Plantillas envase\UA_UCRANIA\124755_SPECTR-AGRO LLC\L_Delantera.btw
' en caso de no encontrar el archivo, devuelve un string vacío ""
@Susensio
Susensio / static_variable_decorator.py
Created April 27, 2020 12:39
Python static variable decorator for functions
# Source: https://stackoverflow.com/questions/279561/what-is-the-python-equivalent-of-static-variables-inside-a-function/279586#279586
def static_vars(**kwargs):
def decorate(func):
for k in kwargs:
setattr(func, k, kwargs[k])
return func
return decorate
import shelve
from functools import wraps
def persistent_cache(cache_file='.cache'):
"""Using shelve module creates a cache that persists across executions.
Depends on repr giving a univocal representation of input arguments.
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
@Susensio
Susensio / property_inheritance.md
Last active April 19, 2024 00:42
Inherit property setter in python 3.7

Python @property inheritance the right way

Given a Parent class with value property, Child can inherit and overload the property while accessing Parent property getter and setter.

Although we could just reimplement the Child.value property logic completely without using Parent.value whatsover, this would violate the DRY principle and, more important, it wouldn't allow for proper multiple inheritance (as show in the example property_inheritance.py bellow).

Two options:

  • Child redefines value property completely, both getter and setter.
@Susensio
Susensio / dynamic_plotting.py
Created September 26, 2018 08:45 — forked from greydanus/dynamic_plotting.py
Dynamic plotting for matplotlib
"Dynamic plotting in matplotlib. Copy and paste into a Jupyter notebook."
# written October 2016 by Sam Greydanus
%matplotlib notebook
import matplotlib.pyplot as plt
import numpy as np
import time
def plt_dynamic(x, y, ax, colors=['b']):
for color in colors:
ax.plot(x, y, color)
@Susensio
Susensio / numpy_lru_cache.md
Last active October 26, 2023 16:10
Make function of numpy array cacheable

How to cache slow functions with numpy.array as function parameter on Python

TL;DR

from numpy_lru_cache_decorator import np_cache

@np_cache()
def function(array):
 ...