---
layout: page
status: publish
published: true
title: Programming Tips
author: Julien Lengrand-Lambert
author_login: jlengrand
author_email: julien@lengrand.fr
author_url: http://www.lengrand.fr
wordpress_id: 431
wordpress_url: http://www.lengrand.fr/?page_id=431
date: 2011-12-28 14:24:01.000000000 +01:00
categories: []
tags: []
comments:
- id: 124
author: The Programming Tips page is back | loup2fu
author_email: ''
author_url: http://www.lengrand.fr/2011/12/the-programming-tips-page-is-back/
date: !binary |-
MjAxMS0xMi0yOCAxNDo1MToyMSArMDEwMA==
date_gmt: !binary |-
MjAxMS0xMi0yOCAxMzo1MToyMSArMDEwMA==
content: ! '[...] Programming Tips [...]'
- id: 126
author: Simply print current function name | loup2fu
author_email: ''
author_url: http://www.lengrand.fr/2011/12/simply-print-current-function-name/
date: !binary |-
MjAxMS0xMi0yOCAxNjo1NTozNCArMDEwMA==
date_gmt: !binary |-
MjAxMS0xMi0yOCAxNTo1NTozNCArMDEwMA==
content: ! '[...] You can also find this tip in my Programming Tips page, in the
Python section. [...]'
- id: 135
author: ! 'Programming tips : New Wordpress section | loup2fu'
author_email: ''
author_url: http://www.lengrand.fr/2012/01/programming-tips-new-wordpress-section/
date: !binary |-
MjAxMi0wMS0wMyAxMzozNzoyMCArMDEwMA==
date_gmt: !binary |-
MjAxMi0wMS0wMyAxMjozNzoyMCArMDEwMA==
content: ! '[...] You will find the content here [...]'
---
Here is a list of all simple tips I have been searching for in the past. I put them here to find them easily !
they are classified by language/topic :
Hopefully one of those tips will help someone :)
BASH
FLV to AVI conversion :
You will need ffmpeg
{% highlight bash %}
$ sudo apt-get install ffmpeg
$ ffmpeg -o /your/flv/file.flv -vcodec mpeg1-video \
-acodec copy -ar 44100 -s 320x240 -y /your/avi/file.avi
{% endhighlight %}
OGG to AVI conversion :
You will need mencoder
{% highlight bash %}
$ sudo apt-get install mencoder
$ mencoder out.ogv -ovc xvid -oac mp3lame -xvidencopts pass=1 -o Winner.avi
{% endhighlight %}
Get the size of a file :
Here are two simple ways:
{% highlight bash %}
$ ls -s file
$ stat file-c %s
{% endhighlight %}
Get the processing time of a function/script:
Simply run the same command prepended with time
{% highlight bash %}
$ time previous_command
{% endhighlight %}
Get the number of arguments in command line:
Use the variable $# to get the number of arguments of previous command.
WARNING: The name of the command stands for one argument!
Get the list of dependencies of a binary:
Simply run the same command prepended with ldd :
{% highlight bash %}
$ ldd previous_command
{% endhighlight %}
Demonize a process :
The command to search for is start-stop-daemon, with start option.
To avoid any output in stdout, use redirection:
{% highlight bash %}
$ command &> /dev/null&
{% endhighlight %}
Launch a process at startup:
A link must be placed in /etc/init.d, using ln -s
{% highlight bash %}
$ mv /etc/init.d
$ ln -s /path/to/file link
{% endhighlight %}
WARNING: A printf in a startup process will lead to a crash as it blocks the remaining processes.
INFO: In embedded Linux, startup processes will have to be named using a Sxx name, where xx is a digit between 1 and 99.
The processes will be run in ascending order, so be careful not to block the system (samba after network, . . . )
Block interruptions (CTRL+C) :
Simply add the line
{% highlight bash %}
trap " 2 3
{% endhighlight %}
where you want to 'trap' the command.
End catching interruptions by adding where you want to stop
{% highlight bash %}
trap 2 3
{% endhighlight %}
Use floats in a script, and convert them back to integers:
The operations can be performed with bc :
{% highlight bash %}
$ VAR=$(echo "2.2/ 10.65" | bc -l)
{% endhighlight %}
To switch back to the int value :
{% highlight bash %}
$ (ceil) INT=${VAR/.*}
{% endhighlight %}
Search for pattern in all files of a folder:
{% highlight bash %}
$ "find ./ -name .svn -prune -o -type f -print | xargs grep -Hi" //pattern//
{% endhighlight %}
The .svn part is used to avoid searching in the subversion folder of my projects.
{% highlight bash %}
$ grep -R //pattern//@@ is also a solution.
{% endhighlight %}
It is even possible to create an alias with it (see Add a one line command in terminal).
Add a one line command in terminal:
You may use some one-line commands lots of times a day in terminal.
You can define aliases to gain productivity:
{% highlight bash %}
$ vim ~/.bash_aliases
{% endhighlight %}
Simply add a new line at the end of the file :
{% highlight bash %}
alias_name = "my_one_line_command"
{% endhighlight %}
Restart your terminal, you're done!
Seconds since epoch:
{% highlight bash %}
$ date -d "$FIRST_TIME" +"%s"
{% endhighlight %}
Directly get the correct shebang for you script:
{% highlight bash %}
$ which //language// > my_script
{% endhighlight %}
Example :
{% highlight bash %}
$ which bash > my_script.sh
{% endhighlight %}
Get the encoding of a file:
{% highlight bash %}
$ file -i //unkown_file_type//
{% endhighlight %}
Remove all .svn folders from a repo:
{% highlight bash %}
$ cd //my_folder///
$ find -name ".svn" -exec rm -rf {} \;
{% endhighlight %}
INFO: Can be performed for any folder type, changing the .svn part
Get information about your Linux version:
{% highlight bash %}
$ cat /etc/lsb-release
{% endhighlight %}
{% highlight bash %}
$ uname -a
{% endhighlight %}
- More information about Kernel (compiler and so on):
{% highlight bash %}
$ cat /proc/version
{% endhighlight %}
Get information about your processor(s):
{% highlight bash %}
$ cat /proc/cpuinfo
{% endhighlight %}
Change default browser in Linux:
{% highlight bash %}
$ update-alternatives &&config x-www-browser
{% endhighlight %}
You will have to choose between all installed browsers in you distro.
Add a user to the sudoers:
{% highlight bash %}
$ visudo
{% endhighlight %}
Search for the line
{% highlight bash %}
@@ root ALL=(ALL) ALL@@
{% endhighlight %}
Add this new line just below :
{% highlight bash %}
user_name ALL=(ALL) ALL
{% endhighlight %}
Get information about you graphical card:
{% highlight bash %}
$ lspci | grep VGA
{% endhighlight %}
You may try this if first is not working :
{% highlight bash %}
$ lspci | grep video
{% endhighlight %}
Add tab completion for sudo commands:
Add
{% highlight bash %}
complete -cf sudo
{% endhighlight %}
in your .bashrc. It can be done simply in running the following command once:
{% highlight bash %}
$ echo "complete -cf sudo" > ~/.bashrc
{% endhighlight %}
Read information in elf files:
{% highlight bash %}
$ readelf -h $1 | grep 'Class\|File\|Machine'
{% endhighlight %}
Sniff on serial interface to read output of a device :
{% highlight bash %}
$ sudo apt-get install jpnevulator
$ jpnevulator --read --ascii --tty /dev/ttyUSB0
{% endhighlight %}
Remove trailing / in path in a script:
{% highlight bash %}
#!/bin/bash
FOLDER=$1
echo ${FOLDER%/}
{% endhighlight %}
PYTHON
Get variable name as a string:
{% highlight python %}
blah = 1
blah_name = [ k for k , v in locals (). iteritems () if v is blah ][ 0 ]
{% endhighlight %}
WARNING : Not very clever however, as variables in Python may have more that one name ! Use with caution!
Replace a part of a table [Numpy]:
{% highlight python %}
small_BW=where((L[temp[ptr-1]]==ptr),1,0)
a=BW[posi_0:posi_1,posi_2:posi_3]
a[:,:]=small_BW.copy()
{% endhighlight %}
Reshape table without size information:
Put -1 as second argument, the info will automatically be processed.
{% highlight python %}
array.reshape(3,-1)
{% endhighlight %}
Concatenate 2 tables [Numpy]:
{% highlight python %}
c=numpy.concatenate((a,b),axis=0)
{% endhighlight %}
Cast data in table to int:
{% highlight python %}
Ndarray.astype(int)
{% endhighlight %}
Write in the end of a file :
Use add mode :
{% highlight python %}
file.open(file_name, 'a')
{% endhighlight %}
Test if variable exists:
{% highlight python %}
try:
print variable
except NameError:
print "Error!"
{% endhighlight %}
Check if variable is one of several choices:
{% highlight python %}
if a in [b, c,d]:
blabla
{% endhighlight %}
Multi instanciation in Python:
{% highlight python %}
a = b = c = 1+1
{% endhighlight %}
WARNING: Those three variables are the same object!
Print function name :
{% highlight python %}
import sys
def tutut():
"""
Dum function displaying its name!
"""
print sys._getframe().f_code.co_name
if __name__ == '__main__':
tutut()
{% endhighlight %}
And here is the result
{% highlight bash %}
[airballman@ubuntu:~]$ python tutut.py
tutut
{% endhighlight %}
C/C++
Block interruptions (CTRL+C):
Include the signal header :
[c]
#include signal.h
[/c]
At the beginning of the main, insert
[c]
signal(SIGINT, fction)
[/c]
with
- fction the function to be started on detection.
- SIGINT the interrupt to be detected.
Some simple basics that helped :
About variables :
- age -> value
- &age -> pointer
About pointers :
- ptr -> ptr value(which is an address)
- *ptr -> variable value placed in the address.
If age is a variable :
- age is its value
- &age is its pointer
If ptr is a pointer :
- ptr is the pointer value (which is an address)
- *ptr is the value of the variable contained in at the address.
Pointers creation:
[c]
int *ptr = NULL; //Is just a creation, the * does not stand for anything else than declaring the pointer.
int age = 10;
*ptr=&age; //ptr is already created, the * now means that whe want to assign its value
[/c]
Those two are equivalent (used for structures):
Define a variable in a Makefile :
- Use the -D option in the CFLAGS
- #define in the C code
Git and GitHub
Simple reminders to manage a project with Git and GitHub interface.
Clone a project from my personal GitHub account:
{% highlight bash %}
$ git clone git@github.com:jlengrand&/projet.git
{% endhighlight %}
Clone a project from another source:
{% highlight bash %}
$ git clone git://git.berlios.de/gpsd
{% endhighlight %}
Push modifications previously locally committed:
Should be performed once in a while to keep remote repository up to date. Do not forget to pull before pushing to avoid conflicts.
{% highlight bash %}
$ git push -origin master
{% endhighlight %}
More information can be found in git documentation
INFO : No need to create a folder first, as a main folder is automatically created for the project.
Electronics
Some basic tipe for new embedded Eletronics programmers (like me ;) )
Use of DDx, PORT and PIN registers:
- DDx: Choice of pins state: Inputs or Outputs
- PORT: Set the outputs state, rules the outputs (ex : set Pin to 0)
- PIN: Reads the inputs states, or toggle values. (ex: Toogle Pin)
Easily set a bit to 0 in a register:
[c]
PPR=PPR & 0b01111111
[/c]
Easily set a bit to 1 in a register:
[c]
PPR=PPR & 0b01111111
[/c]
Debug hardware errors after optimization:
In case your C code does not work any more after Optimization (-O2 -O3)
- Check if global variables are used in interruptions
- Try to set them as volatile
Hazardous hardware resets:
Check if your interruptions are initialized in your code !
Otherwise, the C code will automatically jump to a non-existing address, causing the reset.
I/O problems:
In case of I/O problems in your code, check your Hardware and especially your resistors
Try to unsolder them and run the code.
Embedded electronics main architecture code:
Generally, embedded architecture software is divided into 3 main layers :
- Drivers: Whose job is to interact with Hardware at a low level (Ex : Read spi data)
- Services/Components: Intermediate layer, interface between drivers and Applications
- Application: Higher layer, which aims at achieving the main purpose of the project (Ex: Calculate movement using an accelerometer)
- Here is a simple drawing to get the idea:
[caption id="" align="aligncenter" width="881" caption="Embedded Architecture Drawing"]

[/caption]
INFO: The main idea behind that when you code is the reuse! The application may not be reusable, but drivers and components must !
If you did good, you should be able to use the same application in two architectures, changing only components and drivers.
OpenCV
Memos and Tips about the OpenCV library.
In C/C++:
Place a pointer to the beginning of pixel in an image:
Can be used to naviguate through pixels easily (and more efficiently than some openCV functions).
[c]
char *pImage = iplImage->ImageData
[/c]
Short review of the IplImage structure:
What's really needed to work with an Image
[c]
* IplImage struct {
depth # Number of channels (gray level, color, . . .)
sizeX
sizeY
* ImageData } #Pixels of the image
...}
[/c]
Simple tips for Image Processing optimization in C:
An image is stored in a memory a a long line (n*m size)
Always go trough the buffer way, and not the opposite!
[c]
for (i in nb_lines):
for (j in nb_cols):
//do stuff
}
}
[/c]
and
[c]
for (j in nb_cols):
for (i in nb_lines):
//do stuff
}
}
[/c]
are different !
The second one is 10% faster than the other !
In Python :
Error on compiling OpenCV with Python bindings:
If you get this error when trying to compile OpenCV in Linux
{% highlight bash %}
Could NOT find PythonLibs (missing: PYTHON_INCLUDE_DIRS) in cmake
{% endhighlight %}
Simply try installing python-dev packages.
It should solve the problem.
Subversion
To create a new branch in one of your repositories:
- Copy your trunk folder. This will automatically proceed the mkdir
{% highlight bash %}
$ svn cp trunk -> new_branch
{% endhighlight %}
Update the information
{% highlight bash %}
$ svn update
{% endhighlight %}
INFO: The command is an update and not a commit, as this is the server who performed the operation!
You're done!
Merge your branch back in your trunk:
Move to your trunk folder
{% highlight bash %}
$ cd path/to/my/trunk
{% endhighlight %}
Merge the branch:
{% endhighlight %}
$ svn merge --reintegrate ./^branch
{% endhighlight %}
INFO: The reintegrate option allows continuing to work in the branch even once reintegrated
Some tips:
- A tag is used to get a precise version, fixed in time (Ex : V1.1)
- The trunk must always stay as the main reference to branches and tags (ie. cd /my/trunk before operations).
- Always use the ^ sign to merge and branch folders. It allows to avoid using absolute path.
- The ^ corresponds to /path/to/my/svn/root/folder
- If you're running Windows, you might want to look at tortoisesvn.
Profiling
Simple tips for software profiling using Linux.
Simple steps on using gprof:
gprof is a really efficient prototyping tool designed by Richard Stallman
It is a total graal to exactly know where your bottlenecks are, and which parts of your software have to be optimized first!
- Simply install gprof on your computer (for debian based distros).
{% highlight bash %}
$ sudo apt-get install gprof
{% endhighlight %}
- Compile your C code with the -pg option
- Execute your program, just as usual
- You will see that a gmon.out file was created during the execution
- You can retrieve the results of profiling by running gprof:
{% highlight bash %}
$ gprof your_binary gmon.out >> saved_report
$ vim saved_report
{% endhighlight %}
Simple command-line to search for memory leacks:
Using the Valgrind library.
{% highlight bash %}
$ valgrind --tool=memcheck --leak-check=yes --show-reachable=yes --num-callers=20 --track-fds=yes ./test
{% endhighlight %}
Wordpress
Some very simple tips and hints for wordpress.
Insert an horizontal line in a post :
Simply insert the
tag while in html edition mode .
Insert anchors/links in a section of a page:
This is done in two different steps :
- Define the anchor. You should place the following code where you want the user to be redirected.
[html]your article here.[/html]
- Create a link to the anchor. Depending on what you want, you should insert :
If the anchor is placed in the same page :
[html]my highlighted text[/html]
If the anchor is in another page :
[html]my highlighted text
my highlighted text
[/html]
You can see the result everywhere on this page, in the topic listing :).