Thursday, August 7, 2014

Join odd and even numbered lines

sed:

sed '$!N;s/\n/,/'


awk:

awk 'NR%2==0 {print p","$0;} NR%2 {p=$0;}'


paste:

paste - -


--------------------------
Seems  I like paste most. To join 3 consecutive lines:

paste - - -

Friday, July 18, 2014

Python Profiler

def do_cprofile(func):
    def profiled_func(*args, **kwargs):
        import cProfile
        profile = cProfile.Profile()
        try:
            profile.enable()
            result = func(*args, **kwargs)
            profile.disable()
            return result
        finally:
            profile.print_stats(sort=1)
    return profiled_func

try:
    from line_profiler import LineProfiler

    def do_profile(follow=[]):
        def inner(func):
            def profiled_func(*args, **kwargs):
                try:
                    profiler = LineProfiler()
                    profiler.add_function(func)
                    for f in follow:
                        profiler.add_function(f)
                    profiler.enable_by_count()
                    return func(*args, **kwargs)
                finally:
                    profiler.print_stats()
            return profiled_func
        return inner

except ImportError:
    def do_profile(follow=[]):
        "Helpful if you accidentally leave in production!"
        def inner(func):
            def nothing(*args, **kwargs):
                return func(*args, **kwargs)
            return nothing
        return inner


@do_profile(follow=[fun2])
def fun1():
    fun2()
    pass


@do_cprofile()
def fun2()
    pass

Monday, July 7, 2014

Java cpu profiling with hprof

Set JAVA_OPTS:

-Xrunhprof:cpu=samples,interval=10,depth=8
 
 
There will be a  file called "java.hprof.txt" in your working directory 

Thursday, September 5, 2013

No syntax highlighting in vimdiff

Vim Syntax highlight often mixed with diff color, which makes text unreadable.

Add following line in ~/.vimrc to turn off syntax off in vimdiff

if &diff | syntax off | endif

Wednesday, August 28, 2013

IO Redirection - Swapping stdout and stderr (Advanced)

% (sh myscript.sh 3>&2 2>&1 1>&3) 2>/dev/null
I'm stderr
% (sh myscript.sh 3>&2 2>&1 1>&3) >/dev/null 
I'm stdout

Thursday, August 8, 2013

python 3 line to solve 8 queen

from itertools import *
c = range(8)
print len([v for v in permutations(c) if 8==len(set(v[i]+i for i in c))==len(set(v[i]-i for i in c))])

Tuesday, June 25, 2013

Python overwrite printed line, e.g. text progress

\r will reset the cursor to the beginning of the line.
>>> for i in range(100):
...    time.sleep(1)
...    sys.stdout.write("\r%d%%" %i)    # or print >> sys.stdout, "\r%d%%" %i,
...    sys.stdout.flush()
...