geeknam
geeknam
Nam Ngo
11 Snippets  (81st place)
Published
1 Channel
Created
5 Channels
Following
3 points  (21696th place)
Reputation
Serious Code Generator
Junior Popular Coder
Junior Autobiographer
Senior Autobiographer
Serious Famous Coder
Junior Wise Coder

Recent Snippets See all snippets by geeknam

public by miquelbotanch  264228  5  3  0

Parse git log with PHP to an array

Parse git log with PHP to an array: git_history.php
<?php
// Orginal Author: Ngo Minh Nam
$dir = "/path/to/your/repo/";
chdir($dir);
$output = array();
exec('git log -200 --pretty=format:%at%n%an%n%ae%n%h%n%s',$output);
$history = array();
$field = 0;
foreach ($output as $line) {
	if ($field == 0) {	$commit["date"] = $line;		}else  // unixtimestamp format
	if ($field == 1) {	$commit["author"] = $line;		}else 
	if ($field == 2) {	$commit["email"] = $line;		}else 
	if ($field == 3) {	$commit["version"] = $line;		}else 
	if ($field == 4) {	$commit["subject"] = $line;
						$history[] = $commit;
						unset($commit);
						$field=-1;
	}
	$field++;
}
print "<pre>".print_r($history,true)."</pre>";

;

public by Nam Ngo  2416  0  4  0

python-social-auth mobile support

python-social-auth mobile support: psa_mobile.py
from social.actions import do_complete
from social.apps.django_app import load_strategy
from social.apps.django_app.default.models import UserSocialAuth
from social.apps.django_app.views import _do_login
from social.backends.utils import load_backends
from social.exceptions import MissingBackend



def psa_mobile(request, *args, **kwargs):
    """
    Endpoint used by mobile app to authenticate using OAuth2
    access tokens
    """
    provider = request.POST.get('provider')
    access_token = request.POST.get('access_token')
    data = {'success': False}
    try:
        request.social_strategy = load_strategy(
            request=request, backend=provider,
            redirect_uri=None, *args, **kwargs
        )
    except MissingBackend:
        raise Http404('Backend not found')

    try:
        user = request.social_strategy.backend.do_auth(access_token)
        if user:
            _do_login(request.social_strategy, user)
            data['success'] = True
    except HTTPError:
        pass
    except AttributeError:
        # redirect to register endpoint

    # Return response here
    return data

;

public by yuhua-chen  104551  0  3  0

screen config

screen config: .screenrc
#screen setting
#cjkwidth off
startup_message off

#support 256 color
termcapinfo xterm 'Co#256:AB=\E[48;5;%dm:AF=\E[38;5;%dm'

#statusbar
caption always "%{=u .r} %-w%<%{=ub .Y}%n %t%{=u .r}%+w "
hardstatus alwaysignore
hardstatus alwayslastline "%{= .K} [%l]%<%=%{= .Y}$USER%{= .R}@%H %=%{= .m} %Y/%m/%d%{= .M} %0c "

#key bind
bind b encoding big5 utf8
bind u encoding utf8 utf8
bindkey -k F1 prev
bindkey -k F2 next

;

public by agarman  1897  0  4  0

My .bash_profile

My .bash_profile: bash_profile
# Setup PATH
export PATH=/bin:/sbin:/usr/local/sbin:/usr/local/bin
export PATH=${PATH}:/usr/bin:/usr/sbin:/opt/X11/bin
export PATH=${PATH}:/usr/local/Cellar/go/1.2.1/libexec/bin

# Add stuff for managing multiple JVMs
export JAVA_HOME=$(/usr/libexec/java_home)
export PATH=${PATH}:/Library/Java/JavaVirtualMachines/jdk1.8.0.jdk/Contents/Home/bin
alias java_ls='/usr/libexec/java_home -V 2>&1 | grep -E "\d.\d.\d_\d\d" | cut -d , -f 1 | colrm 1 4 | grep -v Home'

function java_use() {
    export JAVA_HOME=$(/usr/libexec/java_home -v $1)
    export PATH=$JAVA_HOME/bin:$PATH
    java -version
}

# Setup env for VertX development
export VERTX_HOME=/usr/local/Cellar/vert.x/2.1M5/libexec

# Setup env for Android development
export PATH=${PATH}:/Applications/adt-bundle-mac-x86_64-20131030/sdk/tools
export ANDROID_HOME=/Applications/adt-bundle-mac-x86_64-20131030

# some useful aliases & functions
function rand_hex() { 
  cat /dev/urandom | env LC_CTYPE=C tr -cd 'a-f0-9' | head -c ${1:-3};
}

# tmux helpers
alias t='tmux -2 -u'
function tw()  {  t new   -t ${1} -s `rand_hex 3`; }
function ita() {  t -CC a -t ${1}; }
function tn()  { (t has   -t ${1} || t new -d -s ${1} "${2}") && ita ${1}; }

#Emacs <3 forever!
e="emacsclient -s emax -t"
alias e=${e}
alias emux="tn emux \"${e}\""
export ALTERNATE_EDITOR=""
export EDITOR=${e}
export GIT_EDITOR=${e}
export VISUAL=${e}



;

public by geeknam  1732  0  3  0

Python refactors

Python refactors: pyrefactors.py
"""
Use setattr
"""

# Normal
item.price = self.request['price']
item.quantity = self.request['quantity']
item.shipping = self.request['shipping']
item.save()

# Pythonic
item_attrs = ['price', 'quantity', 'shipping']
for attr in item_attrs:
    setattr(item, attr, self.request[attr])
item.save()


"""
Use reduce() or list comprehension for incrementing values
"""
# Normal
total_price = 0
for item in items:
    total_price += item.price * item.quantity

# Pythonic
total_price = reduce(lambda x, y: x + y.price * y.quantity, items, 0)
total_price = sum([item.price * item.quantity for item in items])

"""
Use defaultdict() to avoid initializing dictionaries
"""

# Normal
stats = {}

for line in order_lines:
    if line.product_id in stats:
        stats[line.product.id]['quantity'] += line.product.quantity
        stats[line.product.id]['price'] += line.product.price
        stats[line.product.id]['shipping'] += line.product.shipping
    else:
        stats[line.product.id]['quantity'] = 0
        stats[line.product.id]['price'] = 0
        stats[line.product.id]['shipping'] = 0

# Pythonic
from collections import defaultdict

stats = defaultdict(lambda: defaultdict(int))
item_attrs = ['price', 'quantity', 'shipping']

for line in order_lines:
    for attr in item_attrs:
         stats[line.product.id][attr] += getattr(line.product, attr)


"""
Use operator module with reduce()
"""

# Normal
search_keyword = 'iPhone'
Product.objects.filter(
    Q(title__icontains=search_keyword) | Q(description__icontains=search_keyword) | Q(short_title__icontains=search_keyword)
)

# Pythonic
import operator

keys = ['title__icontains', 'description__icontains', 'short_title__icontains']
conditions = [(k, search_keyword) for k in keys]

Product.objects.filter(reduce(operator.or_, [Q(c) for c in conditions]))


;