Skip to content

Instantly share code, notes, and snippets.

View alanhamlett's full-sized avatar

Alan Hamlett alanhamlett

View GitHub Profile
"""
wakatime.geocoding_utils
~~~~~~~~~~~~~~~~~~~~~~~~
Utils to get location from ip address.
"""
import traceback
import flag # https://pypi.org/project/emoji-country-flag
@alanhamlett
alanhamlett / processHeartbeatsIntoDurations.js
Last active September 19, 2023 20:12
Turn an array of heartbeats into durations by combining heartbeats that are within Keystroke Timeout minutes from each other.
/*
BSD 3-Clause License
Copyright (c) 2023 Alan Hamlett.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
@alanhamlett
alanhamlett / api.py
Last active January 24, 2023 21:03
Serialize SQLAlchemy Model to dictionary (for JSON output) and update Model from dictionary attributes.
import uuid
import wtforms_json
from sqlalchemy import not_
from sqlalchemy.dialects.postgresql import UUID
from wtforms import Form
from wtforms.fields import FormField, FieldList
from wtforms.validators import Length
from flask import current_app as app
from flask import request, json, jsonify, abort
@alanhamlett
alanhamlett / alembic_env.py
Last active October 7, 2022 05:54
Copy of alembic/env.py from wakatime.com allowing usage of --autogenerate flag when creating new schema migrations
from __future__ import with_statement
from alembic import context
from alembic.util.compat import configparser
from sqlalchemy import engine_from_config, pool
from logging.config import fileConfig
import os
import re
import sys
basedir = os.path.abspath(os.path.dirname(__file__) + '/../')
@alanhamlett
alanhamlett / image_utils.py
Last active September 24, 2022 08:07
Utility functions to resize, make square, and optimize (pngquant) images using Python
from io import BytesIO
from subprocess import PIPE, Popen
from typing import Optional
from PIL import Image, ImageFile, UnidentifiedImageError
from PIL.Image import DecompressionBombError
SUPPORTED_IMAGE_FORMATS = ["PNG", "JPEG", "JPEG2000"]
@alanhamlett
alanhamlett / logger.py
Created September 6, 2022 00:21
WakaQ example worker error log handler
from logging import getLogger, ERROR, Formatter, Filter
from logging.handlers import WatchedFileHandler
from wakatime import app
from wakatime.background import wakaq
TASK_LOG_FORMAT = '[%(asctime)s] %(hostname)s %(levelname)s in %(task)s args=%(task_args)s kwargs=%(task_kwargs)s retry=%(task_retry)s: %(message)s'
class TaskFilter(Filter):
@alanhamlett
alanhamlett / amqp.py
Last active October 22, 2021 21:18
send an error email when a Celery worker raises an unhandled exception
# -*- coding: utf-8 -*-
"""
wakatime.amqp
~~~~~~~~~~~~~
Setup for Celery distributed task queue.
"""
import socket
@alanhamlett
alanhamlett / Flask-Login-Example.py
Created April 23, 2014 19:25
Flask-Login Example
# -*- coding: utf-8 -*-
"""
More info:
http://flask.pocoo.org/docs/patterns/wtforms/
http://pythonhosted.org/Flask-SQLAlchemy/
https://flask-login.readthedocs.org/en/latest/
"""
from flask import current_app, request, render_template, redirect, url_for
from myapp.models import User
@alanhamlett
alanhamlett / ajax_setup.js
Last active January 13, 2021 02:18
Sets the X-CSRFToken header for every jQuery ajax non-GET request to make CSRF protection easy. This fixes the example from Django docs here: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (settings.type == 'POST' || settings.type == 'PUT' || settings.type == 'DELETE') {
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
@alanhamlett
alanhamlett / responsive.less
Last active September 30, 2020 18:19
Responsive helper classes for Bootstrap style margins, padding, aligning, and displaying per screen size
/* responsive.less
* ~~~~~~~~~~~~~~~
*
* Responsive helper classes for Bootstrap style margins, padding, aligning, and displaying per screen size.
* Works along with Bootstrap3.
*/
//== Media queries breakpoints from Bootstrap3
// Extra small screen / phone