Skip to content

Instantly share code, notes, and snippets.

# 1.py
# coding: utf-8
def sum1(a):
sum = 0
for i in a:
sum += i
return sum
def sum2(a):
@hanks
hanks / exercises.go
Last active August 15, 2022 07:48
Exercises for a tour of go
// Exercise: Loops and Functions
package main
import (
"fmt"
)
func Sqrt(x float64) float64 {
z := 1.0
for i := 0; i < 10; i++ {
@hanks
hanks / weighted_random_generation.md
Created December 9, 2014 00:53
weighted random generation

Digest from here.

The general way, if weights is a sorted list, it will be faster:

def weighted_choice_sub(weights):
    rnd = random.random() * sum(weights)
    for i, w in enumerate(weights):
        rnd -= w
        if rnd < 0:
 return i
@hanks
hanks / Swift_CLI
Created November 28, 2014 07:54
alias swift in shell
# swift alias
alias swift='/Applications/Xcode6-Beta3.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift'
@hanks
hanks / auto_ssh_add
Created November 28, 2014 07:53
auto ssh-add
# auto ssh-add
SSH_ENV="$HOME/.ssh/environment"
function start_agent {
echo "Initialising new SSH agent..."
/usr/bin/ssh-agent | sed 's/^echo/#echo/' > "${SSH_ENV}"
echo succeeded
chmod 600 "${SSH_ENV}"
. "${SSH_ENV}" > /dev/null
/usr/bin/ssh-add;
@hanks
hanks / pre-commit
Created October 28, 2014 07:19
git pre commit hook to check unsolved conflicts
#!/bin/sh
echo
count=0
echo "Scanning...Conflict Files List:"
for f in `git diff HEAD --name-only --diff-filter=M`; do
if [ -f $f ]; then
if grep -Fxq "<<<<<<<" $f; then
echo " $(tput setaf 1)$f$(tput sgr0)"
@hanks
hanks / meta_test
Created June 2, 2014 04:27
dynamic inherits class
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class A(object):
def __init__(self):
print 'A init'
@classmethod
def foo(cls):
print 'A foo'
@hanks
hanks / getattr_test
Created June 2, 2014 03:46
implement __getattr__ in both class and instance
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class A(object):
def __init__(self, key):
print 'A key', key
@classmethod
def foo(cls):
print 'A foo'
@hanks
hanks / python enum
Last active August 29, 2015 14:01
python enum
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Enum(object):
"""Enum simulation class with auto increment id
>>> a = Enum(['type_1', 'type_2', 'type_3'])
>>> a.type_1
1
>>> a['type_1']
@hanks
hanks / protect_rm
Created May 17, 2014 02:23
protect rm command alais
# replace rm command with mv to Trash to protect remove files or directory miss
function __protect_rm {
mv ${@: -1} ~/.Trash #get last function argument
}
alias rm='__protect_rm'