Tuesday, August 01, 2006

Fwd: Back after many days !

Hi !

I am back after many days of inactivity.

Wednesday, July 26, 2006

PHP : Getting image size

PHP has a very handy function getimagesize() which returns an array of values like width, height, type etc.

Example

$image_size = getimagesize("path/to/the/image.jpg"); ## URLs can also be passed

$image_size[0] is the width and $image_size[1] is the height of the image.

You can also use the following line (picked from php.net) so as to get the values in four different variables directly with the use of list() function.

list($width, $height, $type, $attr) = getimagesize( "img/flag.jpg");

Wednesday, July 19, 2006

Linux : Appending a tar file with xargs

Whereas -c switch of tar command creates an archive, -r is used to append files to a tar files. In the following example, xargs keeps on sending htm files as input to the tar command. These files are appended to htm_files.tar.

find . -name "*.htm" | xargs tar rvf htm_files.tar

Usual way of tar -cvf does not work for the above purpose.

Sunday, July 16, 2006

Linux : Find and Rename files with -exec

Following command finds .html files in the current working directory and changes the extension to .htm. The command illustrates the use of rename with find's exec switch. A quick way of finding and renaming files.

find . -name "*.html" -exec rename .html .htm {} \;

Find is regarded as a power command by many Linux users. The above example supports the claim ! There are many seemingly complicated or time consuming tasks which can be done quickly with commands.

Tuesday, July 11, 2006

Linux : Counting files per directory with Bash command

With commands, you can do many intricate things. Following command which is a small script, counts the number of .htm files in each subdirectory upto depth 2 of the current working directory.

for x in `find . -type d -maxdepth 2`; do y=`find $x -name "*.htm" | wc -l`; if [ $y != 0 ]; then echo $x - $y; fi done

This command is useful for webmasters who spend some time once in a while to figure out number of files in each of the website's subdirectories.

Notes
  1. The value of -maxdepth may be changed as needed
  2. The above command uses current directory (find . -type ...). The dot may be replaced by path of a directory of which the stats is needed.
  3. "*.htm" part of the filename may also be replaced with whatever you want

Thursday, July 06, 2006

Perl : Obfuscation of ARGV

Did you know ?

$a=eval shift @{$x.=chr for qw * 65 82 71 86 * ;$x};

is just another way of saying

$a = shift @ARGV;

Same thing can be done in many different ways. And some ways are intended at making it hard for humans to grasp the code ! Read more about Code obfuscation.

Thursday, June 29, 2006

Perl : Formatting code

Following one liner attempts to format your codes. Works on programs of perl, c, php etc where curly braces - '{ and }', are used for blocks, loops, conditions etc.

perl -pe '$tabs = substr($tabs,1) if (/^\s*}\s*$/);s/^\s*/$tabs/;$tabs.="\t" if(/{[^}]*$/);' -i.bk
filename.c

Files are backed up with .bk extension.

Wildcards are allowed so *.c can be used in place of filename.c.

Monday, June 26, 2006

Perl : Editing files on the command line

With -i switch of perl, files can be edited on command line. You can optionally take a back-up of the old files by providing an extension.

perl -pe 's/\r\n/\n/;' -i file1

Replaces \r\n (dos newlines) to \n from file1.

perl -pe 's/\<\?php/<?/;' -i.bk *.php

Replaces <?php with <? in php files and creates back-up files with .bk extension.

Thursday, June 22, 2006

vi/vim : Changing the tabsize

Default tabstop is 8. To set the tabsize to 4 spaces, just issue this command

:set ts=4

ts stands for tabstop.

To make this a default setting, write this line without the colon ':' in .exrc (.vimrc if you use vim) file.

Wednesday, June 21, 2006

Vim : Dictionary completion facility

Dictionary completion facility is useful when you don't remember the spelling of a word. To make use of this, we must first set the dictionary option so that vim knows where the dictionary is. Following command does that.

:set dictionary-=/usr/share/dict/words dictionary+=/usr/share/dict/words

Now, start typing a word in insert mode.

astro<ctrl+x><ctrl+k>

This shows the first match in the dictionary. You can loop through the matches by using <ctrl+n> (for next) and <ctrl+p> (for previous).

Notes

To understand why the -= and +=, use this command
:help :set+=

Tuesday, June 20, 2006

Regular Expressions : Dealing with special characters like asterisk

This post is for beginners of perl/regular expressions who find it hard to deal with special characters like asterisks if they appear in patterns. For instance, here is a pattern that contains an asterisk
4*3
If you want to replace or remove the asterisk, you will have to escape it with a back-slash ('\') in a regular expression. Following is a sample code.

$x = "4*3";
print "$x\n";

## following line removes the special character asterisk from the scalar $x
## note that the asterisk is 'escaped' by using a back-slash
$x =~ s/\*//;

print "$x\n";


Output

4*3

43

Use of a back-slash ('\') for escaping special characters is common where regular expressions are used. It's also used for escaping spaces in directory-names on shell prompt.

Some examples

character : escaping it
\ : \\
* : \*
+ : \+
/ : \/

Perl : Removing blank lines from a file

You can do intricate things even on command line. The following command prints filename on the command standard output after removing blank lines

cat filename | perl -ne 's/^\s*\n$//; print;'

Notes
  • Replace filename with the path of the file from which you want to remove blank lines.
  • You can optionally redirect the output by using '>' operator to create a new file.

Monday, June 12, 2006

Linux : Installing Packages .... common procedure

This post is for novices who are scared of building/installing new packages on linux :-) Here are the steps.

  1. Download the package. It's normally a .tar.gz file. It could be in some other format like bz2 as well.
  2. Extract it with tar -zxvf package.tar.gz (for .tar.gz files)
  3. Change to the newly created directory with this extraction
  4. Read README files (good practice)
  5. Run on prompt
    ./confgure
  6. then
    make
  7. Become root if you have not already. Default location of installation of almost all new packages is /usr/local so you need write permission to create any new files there.
  8. issue
    make install
You can install packages in other locations by using --prefix=/path/where/you/want/to/install option to ./configure. Learn more about options by using --help (normally) switch of ./configure scripts. All configure scripts may not present you with nice help.

Friday, June 02, 2006

Linux : Synchronizing directories with rdist

rdist is a linux command for keeping identical copies of directories/files over two hosts. File permissions and modification time are preserved if possible. It can use various protocols like ssh, rsh (default). You can have all the synchronization details stored in a file and pass the filename as an argument with option -f to the command as illustrated below.

rdist -f rdist_file

To specify the protocol, use -P option

rdist -P /usr/bin/ssh -f rdist_file

rdist_file is of the following format.

## comments start with '#' sign
/path/on/master/server    ->   remote_server_name  install  /path/on/slave/server ;

-o option is used for specifying an action to be taken on those files on the slave (remote server) which are missing from the master. For truly synchromising two directlries, you can use -oremove to remove the files. The directive then takes the following form.

/path/on/master/server    ->   remote_server_name  install -oremove /path/on/slave/server ;

For more about actions and about the command, see man pages.

Wednesday, May 31, 2006

Linux : crontab does not run perl scripts ?

Recently, I had hard time making crontab run my perl script. The problem was with the environment variable PATH. When given correct path, it started executing the scripts. Following could be the problems

  • Wrong shebang path (the first line that starts with #!). This line tells which command/program to use for execution of the script.
  • Incorrect permissions
If you want to execute a perl script, make sure the output of 'which perl' is used as the path in your shebang.

Monday, May 22, 2006

Away for quite some time

I'm perturbed by Governments resolution to increase the quot for OBC by 27 %. My own view is that reservations, if any, should be based on economic status and not on caste or religion. Does the Indian Government want to divide the society ?

I hope to be back for posting relevant content soon.

Friday, May 12, 2006

PHP : Website Security

PHP files that do database inserts or some other server-side tasks,
should not be accessible via a web browser. All files under Document
Root of a website are accessible by a web-browser. Document Root is
the directory on the server's filesystem. This directory contains the
files/web pages of the website.

To avoid direct access of your php files, you can keep them in a
directory that is not inside Document Root. These files can then be
included into your templates. For web applications, a configuration
file can be included in all files using a relative path. This
configuration file may contain variables like database connection
details and other configuration variables. Include for database
connection too, should reside outside the Document Root.

Variables of help

$_SERVER['DOCUMENT_ROOT']
This followed by relative path of your conf or include files can be
used on most servers.

On shared hosting server, Document Root is not defined for each
website (virtual host), so this variable shows the default value. In
such cases, you can use

dirname(__FILE__)

This gives you the value of the directory containing the file.

Thursday, May 04, 2006

Regular Expressions : Removing blank lines of a file in vi

In this post, I'm going to show you how blank lines of a file can be removed in vi editor with Regular Expressions.

Following is an ex editor command.

:1,$g/^$/d

Notes :
  • ex editor commands start with a colon.
  • 1,$ stands for first line to last line of the file
  • g for global (look for the pattern following everywhere; do not stop after the first match)
  • pattern to look for is placed inside two slashes (//)
  • ^ is for start of line and $ for end of line. Here, there's nothing between the two so the pattern is used for an empty line
  • d in the end is the command to delete matching lines.
This regular expression does not match a line if it contains spaces. If you want to remove those lines as well, here's the modified command.

:1,$g/^ *$/d

Note that there's an asterisk (*) after a space. An asterisk matches the character preceeding it zero or more times.
e.g.

/a*/ matches a,aa,aaa,any number of times.
/\d*/ mathes an integer. \d is for a digit.

Linux : music compositions with sox

Recently, I created a small web application in php and javascript for Tabla compositions. For those who don't know ... Tabla is a percussion instrument. Currently, it is in its primitive stage. By the way, here is the link to it.

I'd like to take it further and add functionality which will allow merging of wav files with sox command that comes with linux distributions. This will allow composer to download his composition in wave format and hear it ! This will require reading the text file and mergin the sound files in the same order. This should be possible with a script (perl/php ?).

I'll soon be collecting .wav recordings of all the basic tabla bols (aksharas) and give it a try. Your comments or ideas are welcome.

Tuesday, May 02, 2006

Linux : date command

Following are some illustrations of the date command.

date

# This prints the current date. Something of this form - "Tue Jan 31 12:16:53 IST 2006"

date +%d
# prints current day of the month

Following examples illustrate getting time related information of a day/date other than the current date

date --date="3 days ago"
# prints date that was 3 days ago

Try these too !
date --date="last Sunday"
date --date="next Sunday"
date --date="Jan 26, 2004" +%a
# prints Day of the week on Jan 26, 2004

Setting the system date. You need to have admin privileges to use --set option.

date --set='+10 minutes'
# Takes system clock forwad by 10 minutes.