My .bash_alises

# remove things to trash
alias rm="trash-rm"

# init ipython with pylab support
#alias myipython="ipython --pylab --pdb"
alias myipython="ipython3 --pylab --matplotlib --pdb"

# record from mic 
alias record="rec -c 1 -e signed-integer -b 16 -r 48000"

# download a website
function dwsite {

    if [ "$#" -ne 2  ]; then
        echo "usage dwsite domains site, (eg dwsite http://math-atlas.sourceforge.net http://math-atlas.sourceforge.net/index)"
    else
        wget --recursive --no-clobber --page-requisites --html-extension --convert-links --domains $1 --no-parent $2
    fi
}

# debug a program using valgrind (memory leaks)
function myvalgrind {
    valgrind --tool=memcheck --leak-check=full -v --show-leak-kinds=all "$1"
}

# show windows scroll (ubuntu)
function showscroll {
    gsettings set com.canonical.desktop.interface scrollbar-mode normal
}

# hide windows scroll (ubuntu)
function hidescroll {
    gsettings reset com.canonical.desktop.interface scrollbar-mode
}

# compile a .tex file for Plos journal
# usage plos file.tex
function plos {
    basename=$(echo "$1" | cut -d . -f 1)
    echo "$basename"
    latex "$basename.tex"
    bibtex "$basename.aux"
    latex "$basename.tex"
    latex "$basename.tex"
    dvipdf "$basename.dvi"    
}

# remove aux files
function clean {
    rm *.aux
    rm *.bbl
    rm *.blg
    rm *.log
    rm *.out 
    rm *.synctex.gz
}

# compile a .tex
# usage mylatex file.tex
function mylatex {
    
    basename=$(echo $1 | cut -d . -f 1)

    pdflatex -shell-escape "$basename.tex" 
    bibtex "$basename.aux"
    pdflatex -shell-escape "$basename.tex"
    pdflatex -shell-escape "$basename.tex"
    
    #clean
}

Some links for python

Matplotlib

  • Accessing to individual axes [1], [2]
  • ax1 = plt.subplot(211)
    plt.plot(t, x)
    plt.subplot(212, sharex=ax1)

  • Get site packages path [1]
  • import site
    In [2]: site.USER_SITE
    Out[2]: '/home/auraham/.local/lib/python3.4/site-packages'
    In [3]: site.USER_BASE
    Out[3]: '/home/auraham/.local'
    In [4]: site.getsitepackages()
    Out[4]:
    ['/usr/local/lib/python3.4/dist-packages',
    '/usr/lib/python3/dist-packages',
    '/usr/lib/python3.4/dist-packages',
    '/usr/lib/dist-python']

notes about erlang

Keeping a spawn process alive

-module(dolphins).
-compile(export_all).

dolphin1() ->

    receive
    
        {From, do_a_flip} ->
            From ! "what about no?~n", dolphin1();
            
        {From, fish} ->
            From ! "thanks~n", dolphin1();
            
        _ ->
            io:format("beh~n") 
            
    %% you can't call dolphin() here,
    %% everything at this point is unreachable!
    end.

This is a shorter version


dolphin2() ->

    receive
    
        {From, do_a_flip} ->
            From ! "what about no?~n";
            
        {From, fish} ->
            From ! "thanks~n";
            
        _ ->
            io:format("beh~n") 
            
    
    end,
    
    %% keep this process alive
    dolphin2().

receive, waiting, and functions
If a given [non spawned] function has a receive block, then such a function will be waiting for an answer.

take(Pid, Food) ->
    Pid ! {self(), {take, Food}},
    receive
        {Pid, Msg} ->    % waiting for a response!
            Msg
    end.

Now, suppose that you call take using an arbitrary pid:

40> kitchen:take(pid(0, 250, 0), milk).
% waiting, press ctrl+g, i, c

To overcome this situation, just add an after clause:

take(Pid, Food) ->
    Pid ! {self(), {take, Food}},
    receive
        {Pid, Msg} ->
            Msg
    after 3000 ->
        timeout.
    end.

This way, if there is no an answer after 3 seconds, the function will return timeout.

Conclusion: don’t add a receive block on a non spawned function unless you know what you are doing.

Flush my mailbox

Add some messages to your mailbox:

44> self() ! self() ! self() ! new_message

Then, flush and print them using your own version of flush:

flush() ->

    receive
        Any -> io:format("~p~n", [Any]), flush()
    after 0 -> ok % if you comment this line, 
                  % it will be waiting for more messages in the mailbox

    end.

This function works as follows.

1. Given that a receive block is involved, flush will read its mailbox looking for a message that match the pattern Any (in this case, all the messages match).
2. Then, the message is printed, removed from the mailbox, and flush is started again.
3. When the mailbox is empty, the function will wait for 0 secs and return ok.

Guards: (orelse,andalso) vs. (;,)

According to lyshfgg, andalso and orelse are preferred to , and ; when exception handling is involved.

if and pattern matching

These two snippets are equivalent. Obviously, the latter is shorter and cleaner.

% if
oh_god(N) ->
    if N =:= 3 -> equals_three;
       N =:= 4 -> equals_four;
       true -> error     % else
    end. 
% guards
oh(X) when X =:= 3 -> equals_three;
oh(X) when X =:= 4 -> equals_four;
oh(_) -> error.
% pattern matching
oh_no(3) -> equals_three;
oh_no(4) -> equals_four;
oh_no(_) -> error.

Also, remember to add a true clause inside an if block. Other atoms and “_” are not allowed.

talking(Animal) ->
    Talk = if   Animal == cat -> "meoow";
                Animal == dog -> "woof";
                Animal == cow -> "mooo";
                true -> "??"                % it must be true, "_" is not allowed within an if block
            end,
        {Animal, "says " ++ Talk ++ "!"}.

about pids and spawned process
The pid of a spawned process does not change after sending several messages. Also, if a function is spawned n times, then there will be n different pids. Consider the following snippet:

-module(process).
-compile(export_all).

start_process() ->
    SpawnedPid = spawn(?MODULE, process, []),       %% spawn process
    io:format("Spawned pid: ~p~n", [SpawnedPid]),   %% print pid
    SpawnedPid.                                     %% return pid as output
    
process() ->

    MyPid = self(),

    receive
        Any ->
            io:format("Message received: ~p, Pid: ~p~n", [Any, MyPid]),
            process()
    end.

In the following, the function process is spawned two times, and two pids are created: Pid1 (0.117.0), and Pid2 (0.119.0).

45> c(process).                    
{ok,process}
46> Pid1 = process:start_process().
Spawned pid: <0.117.0>
<0.117.0>
47> Pid2 = process:start_process().
Spawned pid: <0.119.0>
<0.119.0>
48> Pid1 ! message.                
Message received: message, Pid: <0.117.0>
message
49> Pid1 ! message.
Message received: message, Pid: <0.117.0>
message
50> Pid2 ! message.
Message received: message, Pid: <0.119.0>
message
51> Pid2 ! message.
Message received: message, Pid: <0.119.0>
message

tail recursion and spawned process

The following snippet computes the factorial of a number using tail recursion.

tail_fact(N) -> tail_fact(N, 1).

tail_fact(0, Acc) -> Acc;
tail_fact(N, Acc) when N > 0 -> tail_fact(N-1, N*Acc).

The idea is to keep the result of each operation using a temporary variable called accumulator (Acc). When the recursion process is finished (i.e. the base case is reached), the accumulator is returned. In the following example, the previous function will be implemented using message passing. To this end, we will follow the pattern described in the previous point (about pids and spawned process).

We start with a simple function which takes as parameters the pid of the shell (i.e. the pid that will receive the output of the factorial function) and the number which factorial will be computed.

start_sfactorial(From, N)

This function is almost the same as start_process, previously described. The goal of this function is to spawn the main process, in our case, to compute the factorial of a given number.

start_sfactorial(From, N) ->
    SpawnedPid = spawn(?MODULE, sfactorial, [From]),            %% spawn factorial process
    io:format("Spawned factorial pid: ~p~n", [SpawnedPid]),     %% print pid
    
    SpawnedPid ! {SpawnedPid, N, 1},                            %% start
    
    SpawnedPid.                                                 %% return pid as output    

First, we spawn a function called sfactorial, which takes a single value as parameter: the pid that will receive the answer (From). Then, the spawned pid is printed (SpawnedPid). The next line is the most important one. In this line, the factorial process is started by sending an initial message with this format:

SpawnedPid ! {SpawnedPid, N, Acc}

where SpawnedPid represents the pid of the [spawned] factorial function (sfactorial), N is the number which factorial will be computed, and Acc is our accumulator. At the beginning, the accumulator is 1 (the same as tail_fact). Finally, SpawnedPid is returned, but this step can be omited or replaced by an ok atom.

Our sfactorial function is sketched as follows:

sfactorial(From) ->

    MyPid = self(),
    
    receive
    
        %% base case
        {MyPid, ...} ->
            do_something;
    
        %% otherwise
        {MyPid, ...} ->
            do_something
    end.

As you can see, this function works using messages. Note that only those messages coming from MyPid are received. The base case is implemented as follows:

    {MyPid, 0, Acc} ->
        io:format("Acc: ~p~n", [Acc]),
        From ! Acc;

In this case, the value of N is 0. Therefore, the accumulator is returned. To this end, we send Acc to From‘s pid. That’s it! Additionally, we can output Acc using io:format.

The remaining case is implemented as follows:

    {MyPid, N, Acc} -> 
        MyPid ! {MyPid, N-1, Acc*N}
        sfactorial(From),

First, a message is sent to MyPid:

MyPid ! {MyPid, N-1, Acc*N}

As you can see, the factorial of N is computed using Acc (Acc*N). Then, we ask for the factorial of N-1. Note that we keep this process alive by using sfactorial(From).

Putting all together:

-module(process).
-compile(export_all).

tail_fact(N) -> tail_fact(N, 1).

tail_fact(0, Acc) -> Acc;
tail_fact(N, Acc) when N > 0 -> tail_fact(N-1, N*Acc).


start_sfactorial(From, N) ->
    SpawnedPid = spawn(?MODULE, sfactorial, [From]),            %% spawn factorial process
    io:format("Spawned factorial pid: ~p~n", [SpawnedPid]),     %% print pid
    
    SpawnedPid ! {SpawnedPid, N, 1},                            %% start
    
    SpawnedPid.                                                 %% return pid as output
    



sfactorial(From) ->

    MyPid = self(),          
    receive
    
        {MyPid, 0, Acc} ->
            
            %% end of recursion
            %% send Acc
            io:format("Acc: ~p~n", [Acc]),
            
            %% send Acc to From
            From ! Acc;
            
        {MyPid, N, Acc} -> 
        
            %% send Acc    
            MyPid ! {MyPid, N-1, Acc*N},
            
            %% keep process alive
            sfactorial(From)
    
    end.

Finally, this function can be called as follows:

11> c(process).
{ok,process}
12> process:start_sfactorial(self(), 5).
Spawned factorial pid: <0.70.0>
Acc: 120
<0.70.0>

Maybe you have noticed that this implementation does not use any guards. So,
you can do the following:

103> f(), c(process).
{ok,process}
104> Pid = spawn(process, sfactorial, [self()]).
<0.281.0>
105> Pid ! {Pid, number, 1}.

=ERROR REPORT==== 6-Jan-2016::21:34:42 ===
Error in process <0.281.0> with exit value: {badarith,[{process,sfactorial,1,[{file,"process.erl"},{line,60}]}]}

{<0.281.0>,number,1}

In this case, we are asking for the factorial of an atom: number. That is, we can send anything to Pid, even if it is not a number. In order to avoid this, we can use guards. The next snippet contains a better implementation of our previous function, now using guards. Also, we added a new clause to output a comment when the received message did not matched any pattern.

sfactorial(From) ->

    MyPid = self(),          %% same as SpawnedPid
    receive
    
        {MyPid, 0, Acc} ->
            
            %% end of recursion
            %% send Acc
            io:format("Acc: ~p~n", [Acc]),
            
            %% send Acc to From
            From ! Acc;
        
        %% previous line
        %{MyPid, N, Acc} ->
        
        %% adding a guard   
        {MyPid, N, Acc} when is_integer(N), N > 0 -> 
         
        
            %% send Acc    
            MyPid ! {MyPid, N-1, Acc*N},
            
            %% keep process alive
            sfactorial(From);
            
        %% any other message
        _Any ->
            io:format("Wrong format~n"),
            sfactorial(From)
    
    end.

Now, we can omit meaningless messages.

106> f(), c(process).                           
{ok,process}
107> Pid = spawn(process, sfactorial, [self()]).
<0.289.0>
108> Pid ! {Pid, number, 1}.                    
Wrong format
{<0.289.0>,number,1}
109> Pid ! {Pid, -1, 1}.    
Wrong format
{<0.289.0>,-1,1}
110> Pid ! {Pid, 5, 1}. 
Acc: 120
{<0.289.0>,5,1}