Monday, February 28, 2011

Using rst files -- the easy way

When viewing documents of mahatos, there are text files with rst as their extensions. They reminded me about the reStructureText which I met but got confused and gave it up. This time I tried to figure out how to use it and how to convert it into other formats, for example, the HTML. The following steps and links are my quick notes, just for you who also want to try the rst files very quickly on Ubuntu.

  1. Assume that you have Python on your system already.
  2. $ sudo apt-get install python-docutils (this is the module that gives the utilities of the conversion between rst and other formats)
  3. Download the source package of Docutils
  4. Untar the downloaded package and go to the tools directory, find the rst2html.py, and copy it to a folder contained the cheatsheet.txt (Please download it. It is a text file formatted in rst file, and we will use it for the following test.)
  5. Go to the folder contained the cheatsheet.txt file
  6. $ python rst2html.py cheatsheet.txt cheatsheet.html
  7. You now have the cheatsheet.txt converted to cheatsheet.html, and you can view the cheatsheet.html in your browser
To be brief, use the the tools given by the source package to convert the rst text files into other formats.

Before jump into installing the Dcoutils on your system, you may want to try and see the rendered result online: reST to HTML conversion. Just copy the content of cheatsheet.txt and paste it into the online converter, and click the Render button to view the result. That's pretty cool. :-)

    [Py] SURF tests with mahotas.surf

    I installed mahotas in my Python for the purpose of trying the SURF. There is a simple example on the mahotas document page, but some minor modifications are needed. Here is the modified example code:

    Sunday, February 27, 2011

    Installing Mahotas (image processing in Python)

    I've just learned about SIFT and SURF, and am trying to find some example to learn more.

    For SIFT, it is a patented methodology and seems not possible to be used as the open sourced libraries. For SURF, which has been claimed more robust and faster then SIFT, there is OpenSURF written in C++.

    Based on the information given on Wikipedia, I went for mahotas, which is for image processing in Python, and that's what I need.

    Saturday, February 26, 2011

    [Py] Python+OpenCV+pygame for capturing webcam frames on Ubuntu (10.04)

    Several weeks ago, I tried to find some sample code which can get the frames of the webcam on Ubuntu. Some examples were written in C/C++, some were in Python, and them are all based on OpenCV. I tested them and got some failed. Unfortunately, I have neither enough experience nor enough time to figure out where the problems are, so I started to search some more examples again.

    The first light came from Joseph Perla's blog. He gave an example which worked fine on my Ubuntu 10.04. I post the example with minor modifications (using ImageOps.mirror to flip the image horizontally) as the follows.

    Friday, February 25, 2011

    Stereo vision -- source code testing


    C. Zitnick and T. Kanade proposed an algorithm [1] to compute the depth (or disparity) maps for stereo version. The source code was released for non-commercial usage, and there is a modified version by K. Sokolova and B. Shilo. I suggest you go for the modified version which gives some practical and straightforward descriptions and examples. Also, the modified version offers a complete set to be compiled and executed. However, the source code needs some more minor modifications to be compiled using g++ in Ubuntu 10.04.

    Friday, February 18, 2011

    Bring good stuffs of Linux into Windows

    I love to work with Linux (Ubuntu), especially with its useful commands and tools when I need to write programs or analyse some kind of data. Sometimes, however, I have to cooperate with my colleagues, who are working with Windows and Visual Studio. Maybe I can do the coding works in Ubuntu, but I am not so good to solve all the problems related to hardware and drivers. We are always using cameras to capture images and process the streams in real-time. There are problems for me to run all the programs written by my colleagues in Ubuntu, and unfortunately I have no enough time as well as knowledge to tackle all the problems. Therefore, I have to go back to Windows for some program developments.

    But, the command line environment in Windows is not so convenient as in Ubuntu. Lacking the useful commands and tools might be the most inconvenient. Cygwin is one way to run Linux commands in Windows, but it can only work within the Path in which the Cygwin is installed. Luckily, we have GunWin which provides many of the useful tools for Windows. Just click the ``Setup'' links on the page of  packages, then you will get the tools installed and you can use them directly in the Windows cmd shell.

    For further introduction, please go for the following link:

    Moved from Firefox to Chromium

    I have moved from Firefox to Chromium for several weeks. Firefox is excellent in many aspects, especially its abundant and wonderful add-ons. However, in my own experience, it is not really fast. After some trials and findings, I decided to use Chromium as my default browser.

    I would like to share some experiences here. Some are the excellent features of Chromium, and of course some are not so good.

    Thursday, February 17, 2011

    codepad -- an interesting web service for code sharing

    Check the codepad out. I had no idea about pastebin until meet the codepad website. It's really useful when you want to share some code and output with someone via email, MSN, or other internet media.

    Here is my simple trial on the codepad: http://codepad.org/Oja9hsaI

    Saturday, February 05, 2011

    VirtuaWin -- Virtual desktop manager for Windows

    If you are used to working with virtual desktops or workspaces in Linux, you might feel uncomfortable when working under the Windows environment. Fortunately, VirtuaWin offers an wonderful solution. I have used VirtuaWin in my office PC for at least couples of month. Today I have to do some works in Windows in my laptop, recalled VirtuaWin, and I think this time, I should introduce this good applications to you who read this post. In addition to its excellent functions, VirtuaWin is licensed under GNU.

    After downloading VirtuaWin and installing it, you can check the content of Setup by right clicking on the icon of VirtauWin, which should reside in the bottom right toolbar of the desktop.

    Basic usage by default:
    Alt+Ctrl+Left/Right/Up/Down: to navigate around the virtual desktops
    Alt+Win+Left/Right/Up/Down: to move the working window to the next virtual desktop

    ---
    Note: Its name is VirtuaWin, not VirtualWin.

    Wednesday, January 26, 2011

    Trials of pycam example code

    I am trying to learn something about computer version, and Python is my first choice of the coding tool. After several hours of searching, I found pycam. There are several sample codes given by the pycam. What I have downloaded was the ``pycam-read-only'' folder in which are three subdirectories:

    • c-vs-py
    • openeyes
    • pycam

    To install the pycam, just find the ``setup.py'' in the subdirectory named ``pycam'' and run ``sudo python setup.py install.'' Furthermore, what you need to install might include the follows:

    • python-opencv
    • python-pygame
    • libcv-dev
    • libcvaux-dev
    • libhighgui-dev

    The lib*-dev are (my guess) for the cpp codes, which need to include the cv.h and highgui.h.

    So far, my testing results are:

    1. pycam-read-only/pycam/examples/: Okay, but the fps are low
    2. pycam-read-only/pycam/examples/opencv: Failed. There were errors I don't know how to resolve yet. Only the ``cam-histo.py'' can be executed, after remove the ``cv.CV_VERSION'' at line 88. (the CV_VERSION seems not in my OpenCV.)
    3. pycam-read-only/pycam/pycam/: Failed
    4. pycam-read-only/c-vs-py/c_examples: Okay
    5. pycam-read-only/c-vs-py/py_examples: Some codes showed errors. They are harris_opencv.py, objectDetect.py, and people_only.py.
    ---
    EDIT: New results are given in the new post:
    Trials of pycam example code (2)

      Tuesday, January 25, 2011

      Face detection-- code patch and tests with some drawings

      My colleague introduced me an OpenCV site in Japanese in which many sample codes are available. Most of the sample codes are written in C++, and some are converted to Python also. I copied one sample code, which is used for face detection.

      After testing, I found the sample code has two lines which have to be modified to run properly. The first one seems to be a typo. The variable named as ``storage1'' should be ``storage'' according to other lines of code. The 25th line with variable ``starage1'' should be deleted. Another modification is to change assign the path of Haar-cascade xml files [*] explicitly. The original code gives the xml file without the complete path, and the program cannot find the so-called ``haarcascade_frontalface_default.xml.''

      The patch file:
      @@ -22,9 +22,8 @@
                       sys.exit(-1)
               src_gray = cvCreateImage(cvSize(src_img.width, src_img.height), IPL_DEPTH_8U, 1)
       
      -        storage1 = cvCreateMemStorage(0)
               ## (2)ブーストされた分類器のカスケードを読み込む
      -        cascade_name = "haarcascade_frontalface_default.xml"
      +        cascade_name = "/usr/share/opencv/haarcascades/haarcascade_frontalface_default.xml"
               cascade = cvLoadHaarClassifierCascade(cascade_name, cvSize(1,1))
       
               ## (3)メモリを確保し,読み込んだ画像のグレースケール化,ヒストグラムの均一化を行う
      
      


      Here I tested the sample code with some of my drawings, which can be viewed on my another blog. The results are interesting (at least for me).









      ---
      [*] I have just begun to learn things about computer vision, so I might use some terms wrong.

      Thursday, January 13, 2011

      [Py] Spline function test

      To interpolate data points, Scipy has several modules for this work. For what I am interested in, there are two functions seem to meet my requirement:

      According to the explanations given by the above links, to use UnivariateSpline with s=1 is equivalent to use InterpolatedUnivariateSpline.

      Here is the results of a simple test:

      Code:

      from numpy import linspace,exp
      from numpy.random import randn
      from scipy.interpolate import UnivariateSpline, InterpolatedUnivariateSpline
      from pylab import plot, legend, show
      
      x = linspace(-3, 3, 100)
      y = exp(-x**2) + randn(100)/10
      
      s0 = UnivariateSpline(x, y, s=0)
      s1 = UnivariateSpline(x, y, s=1)
      s2 = InterpolatedUnivariateSpline(x, y)
      
      xs = linspace(-3, 3, 1000)
      ys0 = s0(xs)
      ys1 = s1(xs)
      ys2 = s2(xs)
      
      plot(xs,ys0,'g--',label='UnivariateSpline s=0',linewidth=4)
      plot(xs,ys1,'b',label='UnivariateSpline s=1')
      plot(xs,ys2,'k',label='InterpolatedUnivariateSpline')
      plot(x,y,'ro',label='original signal')
      legend()
      show()
      

      Wednesday, January 05, 2011

      Producing sinusoidal signals


      Sometimes I need a signal of different frequencies for testing, so I wrote a simple Python code to produce compound sinusoidal signal by adding several cosine waves of different frequencies, amplitudes, and phases.

      The code is listed as the follows. (download)
      from scipy import *
      from pylab import *
      
      data_size = 10 # number of sinusoidal waves
      
      A = rand(data_size)
      theta = rand(data_size)
      f = [i for i in range(1,data_size+1)]
      t = linspace(0,10,1024)
      
      y = [0.0 for i in range(len(t))]
      
      for i in range(data_size):
              y += A[i]*cos(2*pi*f[i]*t + theta[i])
      
      plot(t,y)
      show()
      

      Trials of EMD C code

      I found a simple module of EMD in C on google code: realtime-emd. The source code, however, has no main function to invoke the modules. So I wrote one as the follows.

      #include <stdio>
      #include "EmpiricalModeDecomposition.h"
      
      void imfs_output(emdData* emd){
              int i, j;
      
              for(j = 0; j < emd->size; j++){
                      for(i = 0; i < emd->order; i++) {
                              printf("%f ", emd->imfs[i][j]);
                      }   
                      printf("\n");
              }   
      }
      
      int main(void){
              FILE *inputfile = fopen("sinusoid.txt","r");
              int i=0;
              float signal[1024]={0.0};
              emdData data;
      
              while (fscanf(inputfile, "%f", &signal[i]) != EOF){
                      //printf("%d %f\n",i,signal[i]);
                      i++;
              }
      
              emdCreate(&data,i,5,10,0); // problems here
              emdDecompose(&data,signal);
              imfs_output(&data);
              emdClear(&data);
      
              fclose(inputfile);
              return 0;
      }
      


      The main problem is the arguments of the function emdCreate. I am not sure how to set proper parameters to obtain correct results, so please take this clip of code as just a reference.

      You can download the main.c and sinusoid.txt for testing. The input file sinusoid.txt was generate by adding several sinusoidal signals.

      Thursday, December 30, 2010

      [QnA] GL/gl.h and GL/glu.h in Ubuntu 10.04

      I have installed PyODE and tried some examples once when my system was Ubuntu 8.04. Today I think about the PyODE examples and want to study them again. Because my system is Ubuntu 10.04 now, I have to rebuild some necessary environment.

      The most tedious step is to install the cgkit. It has to be installed from the source. During the installation, some more packages or libraries are necessary. Two of them are GL/gl.h and GL/glu.h. Out of my expectation, they have to be installed from different packages.

      To have GL/gl.h:

      $ sudo apt-get install mesa-common-dev 

      To have GL/glu.h:

      $ sudo apt-get install libglu1-mesa-dev

      Wednesday, December 22, 2010

      [DP] Window functions trial

      I am studying the windowed-sinc filters and found SciPy has had a set of window functions to play around.

      Below is my code to generate the plot of several window functions. Note that only 12 of them have been shown. There are four of them need more than one argument and I don't have time to figure out their parameters to get corresponding results.
      from scipy import signal
      from pylab import *


      data_point = 500


      windows =\
      ['boxcar'
      , 'triang'
      , 'parzen'
      , 'bohman'
      , 'blackman'
      , 'blackmanharris'
      , 'nuttall'
      , 'flattop'
      , 'bartlett'
      , 'hann'
      , 'barthann'
      , 'hamming'
      #, 'kaiser'
      #, 'gaussian'
      #, 'general_gaussian'
      #, 'slepian'
      ]


      t = [i for i in range(data_point)]
      steps = 3


      for i in range(0,len(windows),steps):
              for j in range(i,i+steps):
                      w = eval('signal.'+windows[j])(data_point)
                      subplot(2,2,1+i/steps)
                      plot(t, w)
                      axis([0,data_point,-0.2,1.2])
              legend((windows[i:i+steps]),loc='upper left')


      show()

      The result:

      Basically, the window functions return an array which has the size as you assigned. An easy example is as the following:

      >>> from scipy import signal
      >>> signal.blackman(50)
      array([ -1.38777878e-17,   1.48858213e-03,   6.05806481e-03,
               1.40095693e-02,   2.58120534e-02,   4.20553960e-02,
               6.33894512e-02,   9.04534244e-02,   1.23800653e-01,
               1.63824257e-01,   2.10689158e-01,   2.64275593e-01,
               3.24138580e-01,   3.89486780e-01,   4.59182958e-01,
               5.31766851e-01,   6.05499812e-01,   6.78429126e-01,
               7.48468603e-01,   8.13490971e-01,   8.71426720e-01,
               9.20363618e-01,   9.58640963e-01,   9.84932919e-01,
               9.98315897e-01,   9.98315897e-01,   9.84932919e-01,
               9.58640963e-01,   9.20363618e-01,   8.71426720e-01,
               8.13490971e-01,   7.48468603e-01,   6.78429126e-01,
               6.05499812e-01,   5.31766851e-01,   4.59182958e-01,
               3.89486780e-01,   3.24138580e-01,   2.64275593e-01,
               2.10689158e-01,   1.63824257e-01,   1.23800653e-01,
               9.04534244e-02,   6.33894512e-02,   4.20553960e-02,
               2.58120534e-02,   1.40095693e-02,   6.05806481e-03,
               1.48858213e-03,  -1.38777878e-17])

      ---
      Ref:
      1. You can find the source code containing these window functions in the SciPy folder. Mine is located in /usr/lib/python2.6/dist-packages/scipy/signal/signaltools.py
      2. Documents can be found at http://docs.scipy.org/doc/scipy/reference/signal.html
      3. There is a good book about the signal processing for engineers by Steven W. Smith: The Scientist and Engineer's Guide to Digital Signal Processing. The windowed-sinc filters are introduced in Chapter 16.

      [ML] Pretty good tutorial for MLE

      What is Maximum Likelihood Estimation (MLE) exactly? This question has bothered me for a long time. When I was reading papers relevant to ICA, the term MLE appeared again. This time, fortunately, I found a really good tutorial in Wikipedia:


      The first three parts introduce the most fundamental ideas about MLE, and I suggest you, who want to figure out what is MLE, to read these three parts.

      In the next three parts, however, some terms and examples seem come from the biology or genetic aspect. If you get confused with the technical words used in ``twin data'', the ``twin study'' item given by Wikipedia might help you.

      So far, I've had more clear idea about the difference between the probability and the likelihood estimation, which can be summarized as:
      • Probability
        • Knowing parameters: Prediction of outcome
      • Likelihood
        • Observation of data: Estimation of parameters
      There still are some concepts I have not quite known yet, such as the ideas presented in the section of ``Likelihood ratio test.''

      Wednesday, December 15, 2010

      [SW] Installation of the LaTeX formula extension in Inkscape 4.07

      First, the ``Effects'' item has been renamed as ``Extensions'' in Inkscape 4.07.

      Then what you need are:

      To install the textext package, just copy the textext.py and textext.inx files to the folder:
      ~/.config/inkscape/extensions/

      Finally, restart your Inkscape and try it. Note the LaTeX formula might appear in some place beyond your working window, so make sure to zoom out your working area and look around for your formula.

      Monday, December 13, 2010

      [QnA] eth0 disappeared...

      I have no idea why this could happened, yet. My Toshiba laptop lost its eth0 again, and this time I was very sure that the driver had been installed properly.

      Again, I found the following posts which solved my problem:
      http://ubuntuforums.org/showthread.php?t=1459907

      Just edit ``/etc/NetworkManager/nm-system-settings.conf'' and let ``managed=true'':

      Thursday, November 04, 2010

      Floating calculation in bash (with formatted output)

      What I wanted was to get a list of incremental floating numbers, like:
      0.0 0.2 0.4 0.6 ... 2.0

      It is possible to accomplish this mission in bash, with the help of bc. My own script is listed below:
      #!/bin/bash
      for i in {0..20..2}
      do
      #f=$(printf %3.1f `echo "scale=1; $i/10" | bc`) # old version
      printf -v f %3.1f `echo "scale=1; $i/10" | bc` # new version
      echo $f
      done

      The bc command was used because bash cannot handle floating calculation directly.

      Sunday, October 24, 2010

      [QnA] Activate the ethernet card of Toshiba L600 laptop (for Ubuntu 10.04)

      I've bought a laptop (Toshiba Satellite L600) several days ago. Everything seems alright when I inserted the Live CD of Ubuntu 10.04 to play example audio and video files. So I installed Ubuntu 10.04 in my new laptop. After the installation, I tried to connect to the Internet for system upgrade and found the pppoeconf complained with ``no Ethernet card'' messages.

      From the searched results and based on my own incomplete test, here are the steps to activate the Ethernet card of the Toshiba Satellite L600:

      Step 1: Check the type of card.
      $ lspci | grep Ethernet
      04:00.0 Ethernet controller: Atheros Communications AR8152 v1.1 Fast Ethernet (rev c1)


      Step 2: Use the keyword of the card to search the driver. What I found is AR81Family-linux-v1.0.1.13.tar.gz

      Step 3: Untar the downloaded files and install the driver.
      $ make
      $ sudo make install
      $ cd src/
      $ sudo cp atl1e.ko /lib/modules/2.6.32-21-generic/kernel/drivers/net/atlx/
      $ sudo depmod -a

      Step 4: Reboot the system then go for pppoeconf to set up the DSL connection.

      Thursday, October 14, 2010

      [Py] Assign values of one list to another

      It is easy to ``copy'' lists in Python, but it is also easy to get things wrong, especially when you ignore something important like what I did.

      Consider the following situation:
      >>> A = [1,2,3]
      >>> B = A
      >>> B[0]=-1
      >>> A
      [-1, 2, 3]

      What I want is to create a new list B which contains identical elements of the original list A. This doesn't work, however. As you can see in the above test, any modifications made on list B will affect list A. The reason is that when we type ``B=A'', the list B is just another name of list A. They are identical and of course are pointed to the same address. See the following tests:

      >>> B is A
      True
      >>> B.index, A.index
      (, )

      So, if we need an independent list B which has a set of values' copy in list A, use ``list slicing'':
      >>> B = A[:]
      >>> B is A
      False
      >>> B.index, A.index
      (, )
      ---
      Ref: An Introduction to Python Lists

      [Py] Be careful when create multi-dimensional lists

      I wrote a note about the creation of multi-dimensional lists in Python, when I had not yet encountered another problem which have emerged recently. The problem is about appending items to the multi-dimensional lists.

      Consider the following example:

      >>> A = [[]]*3
      >>> A
      [[], [], []]
      >>> for i in range(3):
      ...    for j in range(3):
      ...        A[i].append(i+j)
      ...
      >>> A
      [[0, 1, 2, 1, 2, 3, 2, 3, 4], [0, 1, 2, 1, 2, 3, 2, 3, 4], [0, 1, 2, 1, 2, 3, 2, 3, 4]]

      But what I really want is something like
      A = [[0, 1, 2], [1, 2, 3], [2, 3, 4]]

      My guess is that the creation approach doesn't create a list which contains three independent rows, but just create three rows which actually point to the same address or something like that.

      The solution (perhaps not the best one) is to create the rows in the form of list comprehension:

      >>> A = [[] for rows in range(3)]
      >>> A
      [[], [], []]
      >>> for i in range(3):
      ...    for j in range(3):
      ...        A[i].append(i+j)
      ...
      >>> A
      [[0, 1, 2], [1, 2, 3], [2, 3, 4]]

      Friday, October 01, 2010

      [QnA] Change the permission of viminfo to enable the command histroy of Vim

      After upgrading from Ubuntu 8.04 to 10.04, I found the command history of Vim was missing. The reason is simple: in Ubuntu 10.04, the ~/.viminfo file has a 600 permission so only the root can access it.

      To get the command history of vim back, you may change the permission from 600 to 666. I don't know whether this change has any side effects, however. At least for only one user using one computer, this is a quick trick. :-)

      ---
      Ref:

      Thursday, September 30, 2010

      [QnA] Problems when using fbi/fbgs in virtual consoles of Ubuntu 10.04 (Lucid Lynx)

      I upgraded all my computers (2 PCs and 1 laptop) from Ubuntu 8.04 to 10.04 these days. Most things are fine (and even great!), but there is one thing, the GRUB 2,t has brought me some troubles. I could not use fbi and fbgs in the consoles. Of course I ran into Google several times but got no lucks, until yesterday when I found the following thread and links:


      The second link gives a complete guide.

      FYI: To check the resolution given by framebuffer of your computer, use ``sudo hwinfo --framebuffer'' command in the console.

      Sunday, September 19, 2010

      [SW] Use GIMP to save layers of animated GIF

      It is easy to use GIMP to create animation in GIF format (just use Google and you can find many examples). However, to extract individual layers of an animated GIF is another story, and I can't find a straightforward approach in GIMP.

      Fortunately, the solution has been exist. There is a script by

      Monday, September 06, 2010

      [Py] Rubik's cube game

      Although I am not good at solving Rubik's Cube, I am a fan of it. Of course, I am always wondering whether there are programs which can show a 3D Rubik's Cube in my computer so that I can play the cube interactively. And the answer is YES!

      On Pygame site, there is a wonderful program called Rubik's Cube Game meets all my needs. Actually, I've downloaded and tested it several months ago, but until today I finally get clear steps to make the program run properly. My modifications are as follows.
      1. rename Images/*.PNG to Images/*.png
      2. apt-get install python-opengl
      3. download gameobjects and install it
      4. remove *.pyc
      5. rename *.pyw to *.py
      6. run ``python Rubik's Cube.py''

      Thursday, September 02, 2010

      Converting filenames from UPPERCASE to lowercase

      I searched and found the following thread:
      http://blog.mc-thias.org/?title=rename-files-from-upper-case-filename-to&more=1&c=1&tb=1&pb=1

      Based on the post given by Jadu Saikia, I got the bash script of my own version as follows:
      ls * | sed -e p -e 's/.*/\L&/g' |xargs -n 2 mv

      One new thing I've learned in this example is the ``\L'' part, which can be found in sed's FAQ.

      Wednesday, August 04, 2010

      [Py] Install pygame-1.9.1 in Ubuntu (with running a game: Cave Copter)

      I went to pygame's website to see whether there are some very simple examples for me to begin with. After several trials, I found the pygame version of Ubuntu 8.04 was 1.7 and it was too old to run some games, so I decided to install pygame from the source.

      Things were almost easy. Just download and extract the source files and run the setup.py. Some error messages showed up:
      sh: sdl-config: not found
      sh: smpeg-config: not found


      It means you need to install the following libraries.
      $ sudo apt-get install libsdl-dev libsmpeg-dev

      Ran the setup.py again and I got other warning messages as follows.
      FONT : not found
      IMAGE : not found
      MIXER : not found
      PNG : not found
      JPEG : not found
      PORTMIDI: not found
      PORTTIME: not found

      What I installed were:
      libjpeg-dev libpng12-dev libportmidi-dev libsdl-ttf2.0-dev libsdl-image1.2-dev libsdl-mixer1.2-dev

      Finally, ran
      $ sudo python setup.py
      and got new version pygame work!

      ---
      After installing pygame-1.9.1, I tried to test the game, Cave Copter.

      Cave Copter is a game using pygame. To make it run properly in Ubuntu, there still some minor works to do.

      First, we need to change all the double backslashes in the original CaveCopter.py to single slash. Second, we have to change the *.PNG to *.png so that these png files can be recognized.

      Hope I will have time to play with and to learn something from the source code...

      Thursday, July 01, 2010

      [Py] pty module testing note

      The pty module can be used for pseudo terminals, about which I actually know very little.

      Here are some simple tests I have conducted in my own Ubuntu PC, and I write down it just as a reminding note.

      ---
      Open pseudo terminal pairs

      At the beginning, check the content of /dev/pts:
      $ ls /dev/pts
      0 1 ptmx

      Open another terminal for IPython and then test with pty module as the following:
      In [1]: import pty

      In [2]: pty.openpty()
      Out[2]: (3, 4)

      Now check /dev/pts again:
      $ ls /dev/pts
      0 1 2 ptmx

      Go back to IPython:
      In [3]: pty.openpty()
      Out[3]: (5, 6)

      The content of /dev/pts becomes:
      $ ls /dev/pts
      0 1 2 3 ptmx

      Exit IPython, then check the /dev/pts:
      $ ls /dev/pts
      0 1 ptmx

      ---
      Read and Write test

      To read from the pseudo terminal, it seems necessary to write something first.
      In [1]: import pty

      In [2]: pty.openpty()
      Out[2]: (3, 4)

      In [3]: pty._writen(3,"test")

      In [4]: pty._read(3)
      Out[4]: 'test'

      ---
      Ref:
      how to use /dev/ptmx for create a virtual serial port?
      Python: module pty

      Wednesday, June 23, 2010

      [Py] Work with multiple versions of Python

      In Ubuntu 8.04, the default version of Python is 2.5, and I want to try Python 2.6 without messing up Python 2.5. I followed Andreas Bernauer's article but still had problems.

      During the installation process, I found another useful article which gives also clear guidance:
      Installing multiple versions of Python on Ubuntu from Source

      After installing Python 2.6 successfully, I linked python command to Python 2.6, but got some problems. All the third-part packages (installed in the `site-packages' folder) cannot be seen by Python 2.6. I tried to link the folders but got no luck. Then I noticed the ``setuptools'' which claims:
      Download, build, install, upgrade, and uninstall Python packages -- easily!
      Then followed the steps which also given in Installing multiple versions of Python on Ubuntu from Source. Finally, set link to easy_install, for example:
      $ sudo ln -s /opt/python2.6/bin/easy_install-2.6 /usr/bin/easy_install2.6
      ---
      I installed numpy and matplotlib with easy_install:
      $ sudo easy_install2.6 numpy
      $ sudo easy_install2.6 matplotlib
      The installation of matplotlib got an error message as below:
      error: Setup script exited with error: command 'gcc' failed with exit status 1
      I followed the method proposed here, and installed ``libpq-dev'' but it didn't work. Then I found the solution which is as follows:
      $ sudo apt-get build-dep matplotlib
      So far, one thing is still bothering me. I have no idea how to let IPython work with Python 2.6.

      Wednesday, June 16, 2010

      [Py] Use lambda expression for callback functions of widgets

      Let's see a quotation about Tkinter callbacks:
      A common beginner’s mistake is to call the callback function when constructing the widget. That is, instead of giving just the function’s name (e.g. “callback”), the programmer adds parentheses and argument values to the function
      That's true. I just solved one problem of this kind in my code.

      In short, we cannot use callbacks of widgets in the form of
      Widget(text="some text", command=callback(argv)).pack()

      The reason has been stated clearly in the first link of this post. To call the callbacks which have arguments, we need to utilize the lambda expression.

      I have tried with 3 test programs. They are listed as follows.

      1. from Tkinter import *
      2.
      3. def cb_test(i):
      4. print i
      5.
      6. root = Tk()
      7.
      8. for i in range(5):
      9. Button(root, text=str(i), command=cb_test(i)).pack() # test 1
      9. Button(root, text=str(i), command=lambda:cb_test(i)).pack() # test 2
      9. Button(root, text=str(i), command=lambda x=i:cb_test(x)).pack() # test 3
      10. Button(root, text="Quit", command=root.quit).pack()
      11.
      12. root.mainloop()

      If you would like to try with my codes, please note there are 3 lines denoted as line 9. Keep only one of them and delete the other two.

      [Py] Add new attributes as static variables

      One problem I have met when coding with Python is that there seems no static variables to apply. A straightforward approach is to use the global variables, but it is not such a safe way.

      Several days ago, when I was writing my nth version of my low-pass/high-pass filtering functions, I found a nice method to keep some values of certain variables which would be used in recursive steps. This method is to create new attributes of the called function, and the created attributes could be used as static variables.

      The original information has been given in Ref. and I would like to repeat it again but with my own understanding. The function which have to keep some local variables as static ones could be as follows.

      1. def foo(argv):
      2. if not "your_static_var" in dir(foo):
      3. foo.your_static_var = certain initial values
      4. do something with foo.your_static_var
      5. return foo.your_static_var

      In line 2, we check all the attributes of foo() by the built-in function dir(). If foo() is called for the first time, we could create new attributes with initializations as shown in line 3. I think this is the most brilliant part of the method.

      Next time when you need ``local'' static variables for certain functions, this approach may help.

      ---
      Ref: (see the post by Cameron Laird)
      Python - Static Variables in Python?

      Sunday, June 13, 2010

      [SW] Color toggle -- Firefox plugin to swap foreground and background color

      Many of us use browsers very often, and maybe some of you just don't like the default white color of many web pages. I don't like either.

      I am used to work and view documents in black background with white fonts color, just like the appearance of command line terminals. So I began to search the method which can help me in reversing my browser's foreground and background colors.
      The answer for Firefox is Color toggle by Nathan Baker. Color toggle is a simple plugin which is very easy to use for swapping or toggling colors between two color profiles. Therefore with this plugin, you can toggle your foreground and background colors in very quick key pressing (the default is Ctrl+Shift+u).

      The original looking:

      After toggling:

      Friday, June 11, 2010

      [QnA] Command line rocks!! Combine several data files...

      I have several data files. Each of them has only one column which presents acceleration along one axis. I want to combine them into one single file so that I can read them into my Python program with opening only one file.

      To illustrate the situation, here are some sample contents of the files:

      ACC_X.txt
      126
      127
      129
      127
      137

      ACC_Y.txt
      132
      106
      109
      114
      105

      ACC_Z.txt
      137
      139
      138
      138
      144

      What I want is to combine them in columns within a single files as:
      ACC.txt
      126,132,137
      127,106,139
      129,109,138
      127,114,138
      137,105,144

      The first thing came into my head is using awk. However, I am not familiar with awk script. With brief searching, I found two easy ways in the command line: paste and pr.

      The command using paste could be:
      $ paste -d, ACC_X.txt ACC_Y.txt ACC_Z.txt > ACC.txt

      Or you can use pr like this:
      $ pr -mts, ACC_X.txt ACC_Y.txt ACC_Z.txt > ACC.txt

      The comma in the commands means I am using it as the delimiter or separator.

      Simple and fast. Command line really rocks!

      Sunday, June 06, 2010

      [Py] To show or update images of label

      To show or update images in a label, there is one thing important: You have to keep a reference for the image objects or they will be cleared so you won't see them on your label widgets.

      I totally had no idea about this fact and tried for several hours until I read the following note:
      Note: When a PhotoImage object is garbage-collected by Python (e.g. when you return from a function which stored an image in a local variable), the image is cleared even if it’s being displayed by a Tkinter widget.

      To avoid this, the program must keep an extra reference to the image object. A simple way to do this is to assign the image to a widget attribute, like this:

      label = Label(image=photo)
      label.image = photo # keep a reference!
      label.pack()

      It's also true if you want to show images in sequence and then want to keep the last image when the update stops. Without the ``keep reference'' line, you will see the images updated sequentially and disappear after the last image being showed.

      Saturday, June 05, 2010

      [Py] Update label's content

      I am writing a simple program in Python with Tkinter, and got troubles when I wanted to update the text showed in the label. I have a variable which has been changed in certain function and I want to show its latest value on a label of the root window.

      Before I find the solutions, I think all I need are Label.config() and time.sleep(). However, they didn't make the program run as what I expected.

      Finally, I found the key is the update() function. There are two ways to do what I want, but I don't know the differences between them. Let me just show the test programs I've written.

      [label_test1.py]
      from Tkinter import *
      import time

      class App:
      def __init__(self, master):

      frame = Frame(master).pack()
      master.geometry("200x100")

      var_text = StringVar()
      counter = Label(frame)
      counter.config(textvariable=var_text, font=("arial",60,"bold"), bg="green")
      counter.pack(expand=YES, fill=BOTH)

      for i in range(10):
      time.sleep(1)
      var_text.set(i)
      master.update()

      def main():
      root = Tk()
      app = App(root)
      root.mainloop()

      if __name__ == "__main__":
      main()


      [label_test2.py]
      from Tkinter import *
      import time

      class App:
      def __init__(self, master):

      frame = Frame(master).pack()
      master.geometry("200x100")

      counter = Label(frame)
      counter.config(font=("arial",60,"bold"), bg="green")
      counter.pack(expand=YES, fill=BOTH)

      for i in range(10):
      time.sleep(1)
      counter.config(text=i)
      master.update()

      def main():
      root = Tk()
      app = App(root)
      root.mainloop()

      if __name__ == "__main__":
      main()

      ---
      Ref:

      [Py] Countdown counter

      Here is a countdown counter which counts down in HH:MM:SS format. The original example has given by vegaseat, which counts increasingly. I modified it to be a countdown version as the follows.


      """
      A ``countdown'' counter using Tkinter
      Original version has given by vegaseat 17aug2007
      http://www.daniweb.com/code/snippet216971.html

      This version is modified from the original one
      by thk 2010/06/05
      """

      import Tkinter as tk
      from itertools import count

      def start_counter_down(label):
      counter = count(0)
      begin_time = 10 # sec.
      def update_func():
      left_time = begin_time - counter.next()
      show_hr = left_time/3600
      show_min = (left_time%3600)/60
      show_sec = (left_time%3660)%60
      label.config(text=\
      str(show_hr).zfill(2)+':'+\
      str(show_min).zfill(2)+':'+\
      str(show_sec).zfill(2))
      label.after(1000, update_func) # 1000ms
      if left_time <= 0: label.config(text="Time's up!") update_func() root = tk.Tk() root.title("Counting Down") label = tk.Label(root, fg="red") label.pack() start_counter_down(label) button = tk.Button(root, text='Stop & Quit', width=30, command=root.destroy) button.pack() root.mainloop()

      Tuesday, June 01, 2010

      [Py] Canvas example (correction)

      Here are some GUI examples of Python with Tkinter. One of the example shows how to draw lines in the canvas. However, the source code has some errors. I have tested and corrected the errors as the following lines:

      21c21
      < x =" 250"> y = 250 - (i * 40)
      28c28
      <> scaled.append((100 + 3*x, 250 - (4*y)/5))
      33c33
      < width="1,"> canvas.create_oval(xs-6,ys-6,xs+6,ys+6, width=1,

      Friday, May 28, 2010

      [QnA] Use xmodmap to set modifier keys

      In the previous article, I described how to change the modifier key for wmii from Mod1(Alt) to Mod4(Windows key). That's no problem for my PCs, but not okay for my laptop, an IBM X31. The laptop has NO Windows key, so I cannot just modify the wmiirc file to make things run.

      Fortunately, Google helped me to find the solution again. There is a command called xmodmap to modify keymaps.

      The steps are:
      • Create a file, for example, ~/.Xmodmap
      • Paste the following lines in the created file

      • ! No Caps Lock
        clear lock
        ! Caps Lock as Win key
        add mod4 = Caps_Lock

      • Run xmodmap to enable the settings

      • $ xmodmap ~/.Xmodmap

      ---
      Reference:
      ---
      Edit (2010/06/01):

      After changing Caps Lock key to Windows key, wmii cannot move windows to desktop#2.

      [SW] Change modifier key for wmii

      I have adopted wmii as my main WM for months and it has given pretty good experience in my daily usage. There has been one thing, however, bothering me a bit. The default modifier key of wmii is Alt, which is presented as Mod1 in wmiirc. Because Alt is a frequently used key for tools such as BASH, this default setting could cause some inconveniences. For example, when you want to move forward in BASH commands, Alt+F won't give you the expected moving but will make the working window run in full screen. Fortunately, wmii has been featured as its configurability.

      In my system, which is Ubuntu 8.04, the confiuration files are located in
      /etc/X11/wmii-3.5/

      There are two files look like something to be the configureation file: rc.wmii and wmiirc. To make sure which one is used, use the following commands
      ps aux | grep wmii | grep rc

      In my case, it is the wmiirc file.

      In the beginning of wmiirc, there are several lines which set the keys.
      MODKEY=Mod1
      UP=k
      DOWN=j
      LEFT=h
      RIGHT=l

      I set MODKEY from Mod1 to Mod4 which is the Windows key. Re-login and you can use wmii without the ``Alt conflict'' with many other programs.

      Wednesday, May 26, 2010

      [SW] Internet radio for Ubuntu

      Rhythmbox was the software I used to listen music and internet radios. Due to reasons I don't understand, Rhythmbox does not work properly for the internet radios anymore, and I've tired to find out the solution. I started to search possible alternatives for me to listen internet radios. Firstly I found Exaile and it looked good, but I didn't get its plugin (shoutcast radio) work.

      Finally, I found Tunapie. I installed it and Stremripper via Synaptic. After the installation, I set the audio player as VLC in Tunapie's preference, then everything goes well. :-)

      (But Hot 108 Jamz station cannot be played... Orz)

      Saturday, May 22, 2010

      [Py] Use ``list comprehensions'' to avoid nesting ``for loops'' too deeply

      As I have mentioned in the previous post, I am trying to analyze some data using Python as the programming language. The data sets are from 4 sensor nodes, and each nodes give accelerations in 3 axes. Furthermore, I want to process these data sets in sequential mode. So, the original structure of my program looked like this:

      data = zeros((n_nodes,3))

      for i in range( len(databuffer) ):
      for nodes in range(4):
      for xyz in range(3):
      data[nodes][xyz] = databuffer[nodes][xyz][i]
      if (some conditions):
      do something

      That's crazy! These nested for loops are too deep to be followed. Also, I remember once I read an article written by an experienced programmer, who said if your for loops nested too deep, then maybe you need to redesign you program.

      I had no idea about how to redesign the structure of my program to fit my original requirements. Fortunately, the list comprehensions could resolve this difficulty. Here is the new version using the list comprehensions:

      for i in range( len(databuffer[0][0]) ):
      data = array([databuffer[nodes][xyz][i]\
      for nodes in range(n_nodes) for xyz in range(3)]).reshape(n_nodes,3)
      if(some conditions):
      do something
      The list comprehensions remove two loops and make a conciser new structure.

      Thursday, May 20, 2010

      [Py] Multi-dimensional list

      So far, the list in Python has bothered me a lot. I think it's because I do not understand it enough. These days I've been writing a little program to analyze some data, and encountered unexpected situations which almost got me down.

      One unexpected situation was the multi-dimensional list, or the list of lists. The following page describes exactly what had troubled me:

      (An Unofficial) Python FAQ Wiki (old link)
      How do I create a multidimensional list?

      This surprised me and made me thought again: ``Do I really know how to program in Python?'' The answer is definitely no. The low threshold to begin Python programming made me overestimate my understanding of it. Therefore, I told myself to learn more before stepping further.

      ---
      Another situation surprised me is also about the list creation. The following test shows it:

      >>> a = b = [[]]*3
      >>> a[1] = 1
      >>> b
      [[], 1, []]

      To assign values to list a also affects list b. To avoid this situation, you should create the lists separately.

      >>> a = [[]]*3
      >>> b = [[]]*3
      >>> a[1] = 1
      >>> b
      [[], [], []]

      Monday, May 17, 2010

      [Py] PyODE installation and test

      I read about ODE (no, not the ODE in math) in a thesis last week, and searched it to see what it is. ODE is the abbreviation of Open Dynamic Engine, an library for simulating rigid body dynamics. As a Python fan, it's reasonable for me to search related module of ODE written in Python. The keywords ``python ode'' brought me the PyODE, a set of Python bindings for ODE.

      There are three examples on the PyODE page. I tried to test it, and installed what my system lacked accordingly.

      The installation in Ubuntu is quite easy as usual. My procedures are listed as the follows.

      First, get the PyODE module, which is the basic one to run the 1st example:
      $ sudo apt-get install python-pyode

      Then if you want to run the 2nd example, you need Pygame:
      $ sudo apt-get install python-pygame

      Finally, the 3rd example demands PyOpenGL:
      $ sudo apt-get install python-opengl

      After these steps, I found the best way to get all these examples is to install the documents of PyODE:
      $ sudo apt-get install python-pyode-doc

      You could find the source code of all the three examples in
      /usr/share/doc/python-pyode-doc/examples

      There are two more examples in the folder, but they needs more libraries. To run the ``transforms.py'' example, the error message showed there was no module named ``cgtypes.'' It seems to be in the cgkit package. This package cannot be found in Ubuntu repository, so I downloaded the source and read the README. The SCons and Boost are necessary:
      $ sudo apt-get install scons
      $ sudo apt-get install libboost-dev

      But I couldn't install the package and still get no luck so far.

      I decide not to bother with the Scons and Boost by now. If I have some time, I would like to play with the original 3 examples to see whether I can learn something fun and useful from them.


      When I ran the setup.py to install the package, there came lots of error messages. With some efforts, I noticed one of the error message read there was no file named ``boost/python.hpp.'' And with some more efforts, it came to me that maybe something like ``libboost-dev'' is needed. Therefore, I typed libboost in the terminal and used the Tab key to check available packages. Yes, there was a library named ``libboost-python-dev'' which looked like what I needed, so I installed it by typing:
      $ sudo apt-get install libboost-python-dev

      Then, everything was ready to install the cgkit in the downloaded and extracted folder:
      $ sudo python setup.py install

      The cgkit has been installed, though, the example transforms.py cannot be executed correctly. According to the error message (ImportError: No module named cgtypes), I edited the line in the transforms.py from
      from cgtypes import *
      to
      from cgkit.cgtypes import *

      After the modification, new problem emerged. The window showed up and then closed, with the eorror message given in the terminal:
      freeglut ERROR: Function called without first calling 'glutInit'.

      Then I found the page talking about this issue. So what I had to do was to find somewhere to put the glutInit function call. I tested for several times but totally had no idea where to add the glutInit, then I noticed the keyword in the error message: Function . It took me to the right location of the code to add a line as follows:
      glutInit(argc, argv)
      glutSolidCube(1)

      It didn't work and threw back a name error:
      NameError: global name 'argc' is not defined

      I thought there might be no argument for this function call in the code, so I deleted the argc and argv to make the glutInit be called as the following:
      glutInit()
      glutSolidCube(1)

      Bingo! Although I am still not sure whether the transforms.py runs properly, at least the window showed up with several moving cubes inside.

      By far, the problem to run the transforms.py is solved. However, there is still an example code named vehicle.py cannot be run properly in my system. I have to do other works. Maybe I will come back to find out the solution for the vehicle.py.

      Friday, April 16, 2010

      [Chat] Simple is not so simple -- The hacker emblem and Conway's game of life

      I am not so good at programming, but I am always willing to know or to learn something new about programming. It's natural for me to getting more and more interesting at the open-source and then the hackers' culture. Of course, I'd tried to find some information about ``how to become a hacker'' and the very same sentence made Google bring me the article ``How To Become A Hacker'' written by Eric Steven Raymond.

      Raymond's article is delightful and easy to read. Howevr, I didn't read it thoroughly at the first reading, and the following tiny picture, which is called ``glider,'' didn't attract me too much. I just wondered what it was and then forgot it.

      hacker emblem


      One day, I read one of Raymond's article again, and linked to the FAQ to check out what the ``glider'' is. After I realized what is the glider and what is Conway's Game of Life, all I wanted to say was ``Wow! Cool!'' just as that have been mentioned in Raymond's article.

      The rules of Game of Life are simple, but the outcome is definitely not simple. You choose random cells' locations, then let the cells ``evolve'' under the simple rules. Just watch the ``evolution'' and it looks so vivid and fun!

      I found LifeWiki might be a great page to dive into. You can find many amazing patterns, and play with those patterns online (with your browser's javascript enabled). Also, you can have Xlife in your system to play and test. If you are using Ubuntu, type the following command to install Xlife:

      $ sudo apt-get install xlife

      Finally, 2 videos for your reference:

      Tuesday, March 30, 2010

      [QnA] Use the latest version of exam.cls for preparing exam papers

      When preparing an exam paper, we might want to have two versions of this exam paper: one with answers for teachers and the other has only questions for students.

      The exam.cls makes this task easy. But make sure you are using the latest version of it or you will not have the handy ``ifprintanswer'' function.

      Here is an sample to show how to use the exam.cls with the ifprintanswer function:

      \documentclass{exam} % Set ``exam'' as the document class
      \begin{document}
      \newcommand{\ans}[1]{\ifprintanswers{#1}\fi} % define a new command to simplify
      % the following usage

      \printanswers % Add this line to print the answers.
      % If no answers printing is wanted, just comment this line out.

      \begin{questions}
      \question
      \ans{The answer} The question's description
      \begin{choices}
      \choice The choice A
      \choice The choice B
      \choice The choice C
      \choice The choice D
      \end{choices}
      \end{questions}
      \end{document}

      ---
      Ref:
      Using the LaTeX exam class

      Thursday, March 25, 2010

      [QnA] Add cls or sty files for LaTeX

      We always use certain packages in the latex files, and sometimes the packages are just not there so we need to add them for further working. It's was a big problem for me when I knew very few about the working principle of LaTeX. Now I think I have got a simple and clear process to add packages, that is, *.cls or *.sty, for LaTeX. Here is an example in which I added a so-called exam package for preparing exam papers.

      • Step 1. Search for the exam package and download it from CTAN, and then of course unzip it.
      • Step 2. Make a directory for adding the exam package. In my Ubuntu system, it is:
      /usr/share/texmf-texlive/tex/latex/exam/
      • Step 3. Copy all the files of the downloaded and unzipped exam package to the directory we just made.
      • Step 4. Run the texhash command as root. Done.

      Monday, March 22, 2010

      [SW] Use ps2pdf to convert EPS to PDF

      Sometimes we need to convert the eps files to the pdf format. To utilize ps2pdf is a straightforward choice. However, it's not easy, at least for me, to find out how to use some options. Fortunately, I found one article mentioned about how to fit the eps figure to the output pdf:

      EPS to PDF : how to avoid clipping

      Just to use the ``-dEPSFitPage'' option. More options can be found at the following site:

      How to use Ghostscript

      ---
      (I tried the option ``-dOREIENT1=true/false'' but has no expected results. I cannot find related solution. There is a bug report that followed no further response: ``[Bug-gs] Lanscape view instead of Portrait of a pdf file'')

      Thursday, March 18, 2010

      [SW] Plot the CSV files using Gnuplot

      I have used gnuplot for data plotting for several years, but there has been one minor thing bothering me until today.

      With my previous (not correct) understanding, gnuplot can only handle data files separated by spaces. Therefore, whenever I wanted to visualize the csv files with gnuplot, I had to use awk or sed to remove the commas and then save the results into new files. It made my folders contain redundant data files which were just for using gnuplot. It's a little stupid, I always thought.

      Today I encountered several csv files again, but this time I made up my mind to find the solution out. From the searching results with Google, I found there have been some people asking the same question but without easy solutions given. Then I found a document of old version gnuplot. It gives the right approach: to set datafile separator.

      So, next time when you need to handle the csv files with gnuplot, remember to add the following line in the gnuplot script:
      set datafile separator ","

      Tuesday, March 16, 2010

      [SW] Tips for Gnuplot -- Multiplot with EPS output setting

      It's very often to show several figures in a single plot. With ``set multiplot,'' gunplot can do this work pretty good. There will be some problems, however, when we don't give proper settings for gunplot. One of the problems I've met was the gnuplot did not print out complete plot containing multiple figures with the terminal set as postscript.

      I tried and searched for the solution, and finally got the key. It is better to set the size for the entire plot before the multiplot setting.

      Here is my original WRONG setting structure:
      1. set the terminal
      2. set the output filename
      3. set the size for individual figures
      4. set multiplot
      5. set the origin for individual figures
      6. plot individual figures
      7. unset multiplot
      And the following is the corrected one:
      1. set the terminal
      2. set the output filename
      3. set the size for the entire plot
      4. set the origin for the entire plot
      5. set multiplot
      6. set the size for individual figures
      7. set the origin for individual figures
      8. plot individual figures
      9. unset multiplot
      With the wrong setting structure, we can still get normal output with some terminals such as png. If what we want is something like eps files, then it's necessary to use the right setting structure, which actually makes better sense.

      ---
      Let me show you the (correct) example.
      1 set terminal postscript eps enhanced color solid 20
      2 set output "test_nogood.eps"
      3
      4 set nokey
      5 set size 1,1
      6 set origin 0,0
      7
      8 set multiplot
      9
      10 set tmargin 0.5
      11 set bmargin 0.5
      12 set rmargin 1.0
      13 set lmargin 5.0
      14
      15 set xrange [-25:25]
      16 set ylabel "f(x)"
      17 set noxtics
      18 set noytics
      19
      20 set size 1,0.20
      21 set origin 0.0,0.76
      22 set title "sin(x)" offset 0,-1.0
      23 plot sin(x) w l lt 1 lw 2
      24 set size 1,0.20
      25 set origin 0.0,0.54
      26 set title "cos(x)" offset 0,-1.0
      27 plot cos(x) w l lt 9 lw 2
      28 set size 1,0.20
      29 set origin 0.0,0.32
      30 set title "sin(x)/x" offset 0,-1.0
      31 plot sin(x)/x w l lt 3 lw 2
      32 set size 1,0.20
      33 set origin 0.0,0.10
      34 set xlabel "x"
      35 set title "x*sin(x)" offset 0,-1.0
      36 plot x*sin(x) w l lt 8 lw 2
      37
      38 unset multiplot
      39
      40 reset
      41

      You will get the following plot:
      If you change line 5 as ``set size 1,0.20'' and comment out lines 6, 20, 24, 28, and 32, the output result will be as the following plot:
      It gives only the last part of the eps file.

      ---
      References:
      Gnuplot FAQ: 7.6 My output files are incomplete!
      Visualize your data with gnuplot

      Friday, March 12, 2010

      [SW] Convert XLS to CSV

      I got a bundle of xls files and want to extract their data for further analysis. The first thought occurred to me was to find some command line tools to help me convert all the xls files into some kind of text files. Then I found xls2csv, which can be got via apt-get by installing catdoc. So what you need is typing
      $ sudo apt-get install catdoc
      in your Ubuntu terminal.

      The catdoc is useful when you want to take a look at the textual information in doc files.