Linux Ask!

Linux Ask! is a Q & A web site specific for Linux related questions. Questions are collected, answered and audited by experienced Linux users.

May 222010
 

How to debug in Python?

Answer:

Assume you have a simple python script like:

a = 1
b = 2
c = a + b
print c

To enable debugging, add the following line at the top of the program

import pdb

and in the line you want to break, add

pdb.set_trace()

So the whole program become:

import pdb
a = 1
b = 2
pdb.set_trace()
c = a + b
print c

When you execute the script by python test.py, you will in the debug mode.

Some useful commands:

1. Print variables: p a
2. Step over: n
3. Continue: c
4. Quit: q

Apr 302010
 

Character classes not working in grep command

Seems grep / egrep does not support character classes, e.g.

# find -type f | grep -e '[\d]'

It finds all the file contains the character d, instead of decimal number(s).

Answer:

By default, egrep only understand the POSIX Basic Regular Expressions (BRE) standard, so what would like to use is:

# find -type f | grep -e '[[:digit:]]'

or you can force to interpret as a Perl regular expression

# find -type f | grep -P -e '[\d]'

Apr 292010
 

Strict comparison in PHP

Answer:

PHP has two ways to compare two variables, type-safe and type-less, e.g.

Type-safe

print ( "123" === "123" ); // print 1
print ( 123 === 123 ); // print 1
print ( 123 === "123" ); // print nothing

Type-less

print ( "123" == "123" ); // print 1
print ( 123 == 123 ); // print 1
print ( 123 == "123" ); // print 1

Reference: http://php.net/manual/en/language.operators.comparison.php

Apr 282010
 

Floating point precision in PHP

Answer:

It is typical that simple decimal fractions like 0.1 or 0.7 cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9.

E.g.

$a = 0.1;
$b = 0.7;

print $a + $b;
print (( $a + $b ) * 10);

Reference: http://www.php.net/manual/en/language.types.float.php

So, never compare two floating numbers in your program.