Sunday, November 24, 2013

Working on a Python + Curses terminal application

I am working on a Python project of my own to create some console applications using curses. Due to the learning curve of Curses, I decided to write this post to keep track of things.

—– Nov. 24

Completed the menu + dynamic content output to the welcome screen. Working on Direct Command mode, users press ‘space’ to switch to direct Command and use shortcuts to perform certain operations.

—– Nov. 26

Completed direct command override at any interface starting with “:”.

—– Dec. 10

Written with StackEdit.

Sunday, September 22, 2013

On my way solving all problems in Project Euler

Recently I just found solving problems listed in Project Euler a great fun. Last time I decided to crack something like that, it was the very classic python challenges. From that I learned what exactly this sentence means:

Life is short, use Python

So let me try to crack all problems in Project Euler. If you are reading this and want to / just started / enjoying solving those problems, please be so kind as to add me as a friend on PE:

26855429531387_776918073bc1640d08f267ff8f653358

Thanks. Be a happy problem solver.


Update 1: Sep 23

Solved 46 problems ordered from most people solved to least...

Written with StackEdit.

Tuesday, September 3, 2013

Patching up SublimeREPL

Some may find that the SublimeREPL package is not working out of the box for MIT-Scheme, a MsgBox shows up that reads:

no such file or directory

Ok this is the fix:
Sublime -> Browse Packages -> find REPL -> find the folder for Scheme -> Main.sublime-menu

Line 29:

"extend_env": {"INSIDE_EMACS": "1"},

Change it:

"extend_env": {"INSIDE_EMACS": "1","PATH": "/usr/local/bin"},

Try, it should work.

And you may also want to add this to your REPL configuration

Written with StackEdit.

Monday, August 26, 2013

Two useful python configurations

1 Manually select the source of packages when using easy_install

Put such a file in your $HOME$ path:

[easy_install]
index-url=http://mirrors.tuna.tsinghua.edu.cn/pypi/simple

and name the file as : pydistutils.cfg
From now on the easy_install will use the index-url you just defined as a preferred source of packages.

More useful settings can be found here: Configure pydistutils.cfg - example python distutils config file

2 A python snippet to make updating easy_install package update easier

from setuptools.command.easy_install import main as install
from pkg_resources import Environment, working_set
import sys

plist = [dist.key for dist in working_set]

def autoUp():
    for p in Environment():
        try:
            install(['-U', '-v'] + [p])
        except:
            print "Update of %s failed!"%p
        print "Done!"

def stepUp():
    for p in Environment():
        a = raw_input("updating %s, confirm?(y/n)"%p)
        if a== 'y':
            try:
                install(['-U'] + [p])
            except:
                print "Update of %s failed!"%p
        else:
            print "Skipping %s"%p
        print "Done!"

print "You have %s packages currently managed through easy_install"%len(plist)
print plist

ans = raw_input('Do you want to update them... (N) not at all, (O) one by one, (A) All')

if ans == "N":
    sys.exit()
elif ans == "O":
    stepUp()
elif ans == "A":
    autoUp()
else:
    pass

Written with StackEdit.

Saturday, August 10, 2013

Recent updates

Since I got Day One app on all of my Apple products, I haven't have log on this blog for quite a while.

Recently I have been developing a few quant strategies with a hedge fund in Wall Street. So my day time job is to program in C and Python. I use python to rapid-prototype ideas, and use C to develop serious and dependable apps to trade. 

Some packages I would really love to recommend : 


An data source for most mainstream languages and excel. The data is clean and neat.


An open source backtest framework for python. You can use Quantopian for 1 min data resolution. And Zipline for more flexibility and local backtest.



And my favorite IDE for python and C:


I didn't mean to be political in editor war, but gVim is so f***** superior and comfortable to use. 


In the end I would like to post an Instagram photo. The cloud is simply dream-like that afternoon.







Friday, May 3, 2013

HJKL for direction keys in Ubuntu

Hi,

I recently came back to Ubuntu for some developing works. One thing I really miss from my Macbook Pro is the global remap setting of the very handy HJKL keys and some other shortcuts.

So I decide to replicate it.


Actually, there are more than one kinds of Shift key in the world, the one we used everyday should be literally called as Level2_Shift. If you would open your keyboard remap file by this terminal command:

vi /usr/share/X11/xkb/symbols/us

You would see how this actually works. For each key, the original mapping to the alphabet or function is defined, in addition, a second mapping to the capital letters are defined as well.

    key <AE06> {        [         6,    asciicircum     ]       };

The ^ key was defined as Level2, and the Shift key we used normally would map the keystroke to ^ rather than '6', the level 1 stuff.

So the basic idea would be to make the Caps key itself as a Level3_Shift, and make the directional key as the Level3 function of HJKL.

Thus:

I would add such a few lines in the first part of the file ( with sudo ):

sudo vi /usr/share/X11/xkb/symbols/us

And the lines are:

key <AC06> {    [       h, H, Left      ]       };
key <AC07> {    [       j, J, Down      ]       };
key <AC08> {    [       k, K, Up        ]       };
key <AC09> {    [       l, L, Right     ]       };

key <CAPS> {[ISO_Level3_Shift]};

//---------------------------------------------------------------------

Save the modification to disk using command ":wq", and log off, log on

You should notice the caps won't work as before. And the directional keys are just more handier.

If you still want the Original caps back, you may consider using Caps + A as the original Caps, they are close to each other and are easy to press as one key:

Change one more line : {[ a, A, CAPS]};

Happy HJLK
 

Monday, April 8, 2013

The best camera is the one you could always have with you.





The best camera is the one you could always have with you.




via Tumblr http://jiamingkong.tumblr.com/post/47520277136

Thursday, March 28, 2013

Remapping the CAPS lock key

We don't really need the caps lock key, do we?
And we don't want to move the right wrist to press direction keys. And we don't want to move both wrists to press fn + delete to forward delete...


So I figured out a way of remapping this stuff to a Hyper function key.

Hyper = control + option + command + shift...

Actually no software would require a user to press all four modifier keys for any shortcut, because this is simply counter-intuitive. So just remap the caps key to Hyper key...

1.
PCkeyboardHack

Install this and reinstall... RMBP tooks 10 seconds to do a cold boot up. Hoorah~

If reboot is painstaking for you, pls open a safari, or anything big, like pages, matlab with files open and unsave. Download this one and the one I am talking about in step 3, install PCKH, use safari or whatever to stop computer from auto reboot, and install KR4MB. Then reboot...


Open this software, the first item you will see is to modify the caps key... The default setting is to remap it to delete key or escape, which you won't use a lot until you start coding in VIM-like environments.

Set this key to remap at keycode 80, which is for hyper.

2.
System Preferences

Open the system preferences, find Keyboard- > Modifier keys- change the caps key to no action...

From now on every caps key you press, system will simply pass it through to PCKeyboardHack...


3.
KR4MB

This weapon could help you combine the Hyper key you just got, and some other keys, to make them more functional.

It could take a while to modify the setting, since basically modifications are in the private.xml file... So I am providing my version of private.xml

Open KR4MB ( simply type KR4MB in spotlight ).
Misc & Uninstall -- > Open private.xml...
From the finder window poped out, copy and paste my private.xml to replace the old one...

Go back to the Change tab in KR4MB
Reload XML

And check everything you need...

Basically I made another set of movement keys. 

caps + tab = traditional caps...

caps + H  = left
caps + J   = down
caps + K   = up
caps + L   = right

caps + Y  = Home
caps + U  = PageDn
caps + I    = PageUp
caps + O = End

caps + D  = forward Delete ( traditional delete on windows)
caps + space = enter

It will takes one or two days to get accustomed. After that you won't stop using this long-ignored key...

Good luck


Friday, February 8, 2013

One liner Asian option pricer

function [C] = BLM(n, S_0, K, u, d, p, T)
    C = mean(max([mean(cumprod((u-d) .*(rand(n, T) < p) + d,2), 2) * S_0 - K, zeros(n,1)]));
end

Fully vectorized for performance.

Tuesday, January 29, 2013

Sublime Snippet: LaTex template

Instruction

a very useful Sublime Text snippet to save your time inputing latex templates.

<snippet>
    <content><![CDATA[

\documentclass[]{article}
\usepackage[letterpaper, margin = ${1:1}.in]{geometry}
\begin{document}
\title{${2:Title}}
\author{${3:YourName}}
\date{Today}
\maketitle

${4:Content}

\end{document}
]]></content>
    <!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
    <!-- <tabTrigger>hello</tabTrigger> -->
    <!-- Optional: Set a scope to limit where the snippet will trigger -->
    <!-- <scope>source.python</scope> -->
</snippet>

Instruction

Open sublime text 2. Tool -> New Snippet . Copy and paste the above codes, save it in the recommended path when you press Command + S , remember to add the suffix ".sublime-snippet"

I personally recommend : latex.sublime_snippet

To use it

In any new document, Command + Shift + P , type in : latex ( or any other name you saved your snippet file), and press tab.

Keep pressing tab to see magics.

On modifying

Feel free to modify the above code, for example add packages you use very often, for the very magical placeholder like, the format is

${#:Predefined value}

where # is the number of the placeholder, Predefined value is any string you would probably use.

Say I don't always use \Today, I prefer manually enter it, I change the corresponding line to this following one:

\date{${4:Today}}

And I will make the original "Content" placeholder into # 5, which is: #{5:Content} rather than 4.

Special Thanks to Web-design-Weekly

Tuesday, January 1, 2013

Installing Python and its friends on Mac

1 Installing Homebrew, Python, and PIP

1 Installing Homebrew, Python, and PIP

Both Homebrew and PIP are package managers available on Mac.

  • Homebrew makes plenty of softwares and packages more accessible.
  • PIP makes packages/modules for Python easier to manage.

1 Homebrew

Paste this into the terminal:

sudo ruby -e "$(curl -fsSkL raw.github.com/mxcl/homebrew/go)"

And set the path so the Homebrew knows where to put your stuff:

export PATH=/usr/local/bin:/usr/local/share/python:$PATH

Normally you will find your scripts and packages installed under:

/usr/local/share/python/

2 Python

This is a one liner:

brew install python

3 PIP

We will install PIP using Homebrew:

easy_install pip

2 Installing NumPY, SciPY

1 NumPY

sudo pip install numpy

2 SciPY

brew install gfortran
sudo pip install scipy

3 Running Python

Start the IDLE that came with the installation of Python, and try these following lines:

import numpy
import scipy

Try to build it. It should work.

The references to these two very useful modules are easily accessible by one or two google search. I don't want to bother you guys with functions detail. Try this:

help(numpy)

3 Make a cosy room for Py

The original IDLE isn't great enough for running Python, I personally recommend you to use Sublime Text. It's just simply awesome.

Remember to select the build system to be Python or Automatic (which selects the correct one based on the extension of the filename).

Happy coding with Python!

BTW, happy new year!