Skip to content

Instantly share code, notes, and snippets.

View laginha's full-sized avatar

Diogo Laginha laginha

  • Coimbra, Portugal
View GitHub Profile
@laginha
laginha / typed.py
Last active December 8, 2019 10:28
Convert lists and dictionaries to type instances, for js-like objects and ruby-like lists
from operator import getitem
from functools import reduce
def getindex(array, index, default=None):
'''
getindex(['foo', 'bar'], 1) => 'bar'
getindex(['foo', 'bar'], 2) => None
'''
try:
return array[index]
@laginha
laginha / requests.js
Created October 7, 2019 10:56
fetchJS wrapper to create resources and make requests
const request = (url, options) =>
fetch(url, {
'Content-Type': 'application/json',
...options
})
.then(response => {
if (response.ok) return response.json()
throw new Error(response.status)
})
@laginha
laginha / calculadora.py
Last active August 4, 2016 10:50
Descontos para trabalhadores independentes
# -*- coding: utf-8 -*-
class Imposto(object):
def __init__(self, rendimento_anual_bruto):
self.rendimento_anual_bruto = rendimento_anual_bruto
self.rendimento_anual_de_incidencia = self.rendimento_anual_bruto * self.TAXA_DE_INCIDENCIA
self.rendimento_mensal_bruto = rendimento_anual_bruto /12
self.rendimento_mensal_de_incidencia = self.rendimento_anual_de_incidencia /12
class SegurancaSocial(Imposto):
@laginha
laginha / dictionary.py
Created August 6, 2013 16:01
Get to a dictionary's value easily without explicitly checking the existence of previous keys in the dictionary tree.
class Dictionary(dict):
'''
d = Dictionary( {'foo': {'bar': 'foo'}} )
>>> d['foo']['bar']
'foo'
>>> d['foo']['foo']['bar']
{}
instead of:
import socket
def import_settings(configs={}, default=None, base=None):
'''
Args:
configs - dictionary of {hostname : settings-module} - settings mapped to current hostname is loaded.
default - settings-module - loaded if current hostname not in configs.
base - settings-module - loaded regardless of the other args.
import_settings(
from django.conf.urls import include, patterns, url as django_url
import re
def url(pattern, view, kwargs=None, name=None, prefix='', constraints={}):
'''
url('/path/:id/to/:something/', some_view, constraints={'id': r'\d{4}'})
'''
def convert(match):
name = match.group(1)
@laginha
laginha / geoipcity_crawler.py
Created February 5, 2012 19:06
Lookup IP addresses and get geolocation using GeoIP City Demo
from requests import post
import re, json, optparse
class GeoIpCity:
@staticmethod
def request( ip ):
response = post( "http://www.maxmind.com/app/lookup_city", {'ips': ip} )
return ''.join( [i.strip() for i in response.content.split('\n')] )
@laginha
laginha / whatismyip_crawler.py
Created February 5, 2012 15:45
Get geolocation information from whatismyipaddress.com
from requests import get
import re, json, optparse
class WhatIsMyIP:
@staticmethod
def request( ip ):
clean_html = lambda x: ''.join( [ i.strip() for i in x.split('\n')] )
url = lambda x: "http://whatismyipaddress.com/ip/%s" %x
response = get( url(ip), headers={'User-Agent': 'Mozilla/5.0'} )
@laginha
laginha / csv_ureader.py
Created February 3, 2012 23:48
Unicode csv reader
from unicodedata import normalize, combining
def unicode_( s ):
"""
Convert string to unicode & Remove accents
"""
ustr = u''.join( ucharlist( '%s'%s ) )
nkfd = normalize( 'NFKD', ustr )
return u''.join( [ c for c in nkfd if not combining(c) ] )
@laginha
laginha / randomizer.py
Last active December 6, 2019 22:05
Interface built over python module random
import random, math
MAX = 100
MIN = 10
class Randomizer:
def __init__(self):
self.choice = random.choice
self.list = lambda f,m: [ f() for i in self.range(0,m) ]
self.hash = lambda a,b: dict( zip( a(), b() ) )