Monday, November 10, 2008

Perl: Rounding off Decimal Digits


#!/usr/bin/perl
# Filename: kb_converter.pl
# Description: Convert values from Bytes to KiloBytes
use strict;

my $val;
my $argc = @ARGV;
if($argc == 1) {
$val = shift;
} else {
$val = 12345;
}

# 1KB = 1024Bytes
my $val_kb = $val / 1024;
my $val_kb_rounded = sprintf("%.2f", $val / 1024);
print "Not Rounded Answer:\n$val Bytes = $val_kb KB\n";
print "Rounded Answer:\n$val Bytes = $val_kb_rounded KB\n";

Wednesday, August 13, 2008

The Unix/Linux 'search' command

How to find files in Linux or Unix using 'find'


The 'find' command is very effective in searching for files in my Unix or Linux box. Here's how you do it:

# find <path> -name "<filename>" -print

Example 1: Let us search for the file 'sshd' from the root('/') directory.

# find / -name "sshd" -print
./usr/sbin/sshd
./usr/src/etc/pam.d/sshd
./usr/src/etc/rc.d/sshd
./usr/src/secure/usr.sbin/sshd
./etc/pam.d/sshd
./etc/rc.d/sshd
#

So, there it is, the 'sshd' file can be found from those six different locations.

Searching a File containing a particular text string in Unix or Linux


Again, I use the 'find' command for this. The syntax is as follow:

# find <path> -exec grep "<search_string>" '{}' \; -print

Example 2: Let us search for files that contains the string "dhclient_start" from the etc('/etc') directory.

# find /etc -exec grep "dhclient_start" '{}' \; -print
start_cmd="dhclient_start"
dhclient_start()
/etc/rc.d/dhclient
#

The output tells us that it has only found one file that contains the string we were looking for. It can be found inside the file '/etc/rc.d/dhclient'.

This is my simplified 'search' command


I tried to simplify the find command by creating a shell script which will accept only three parameters:

# search <search_path> <search_type> <search_string>

Where:
search_path:
ex. /usr/local
search_type:
file - search for a file/directory
content - search for a file content
search_string:
- the filename or the file content you want to search

Example 3: Let us search for the file 'sshd' from the root('/') directory.

# search / file "sshd"
./usr/sbin/sshd
./usr/src/etc/pam.d/sshd
./usr/src/etc/rc.d/sshd
./usr/src/secure/usr.sbin/sshd
./etc/pam.d/sshd
./etc/rc.d/sshd
#

The output is the same with Example 1 but as you notice we only have three parameters in our command which makes is simpler to understand.

Example 4: Let us search for files that contains the string "dhclient_start" from the etc('/etc') directory.

# search /etc content "dhclient_start"
start_cmd="dhclient_start"
dhclient_start()
/etc/rc.d/dhclient
#

The output is also the same with Example 2 and again the command only take three parameters.

Here is the script, you can copy and paste this script and save it to a file named 'search'. After saving the file, change the permission of the file to '+x' and copy it to '/usr/local/bin'.

#!/bin/sh
# Filename: search
# Description: A simplified find command
# Author: Obispo

searchPath=""
searchType=""
searchString=""
findcmd="/usr/bin/find"
scriptUsage="
Usage:
${0} <search_path> <search_type> <search_string>
search_path:
ex. /usr/local
search_type:
file - search for a file/directory
content - search for a file content
search_string:
- the filename or the file content you want to search
"

# Script Usage
display_usage()
{
echo "${scriptUsage}"
exit 1
}

if [ "${1}" = "" ]; then
display_usage
elif [ "${2}" = "" ]; then
display_usage
elif [ "${3}" = "" ]; then
display_usage
else
searchPath=${1}
searchType=${2}
searchString=${3}
fi

case "${searchType}" in
file)
${findcmd} ${searchPath} -name "${searchString}" -print
;;
content)
${findcmd} ${searchPath} -exec grep "${searchString}" '{}' \; -print
;;
*)
display_usage
;;
esac

exit 0


Enjoy!


Thursday, July 24, 2008

English to Bisaya Language Translator

Hmmm... I have successfully created an English to Bisaya Language Translator about 3 years ago, as a project in my Natural Language Processing (NLP) subject and I developed it using Visual Basic 6. Luckily last weekend, as I tried to clear some trash in my room, I found the Object Schema documentation of my project!

This leads me to an idea of creating an online English to Bisaya Language Translator project using PHP... Do you think this is a great idea? I have seen that the number of tourist people here in Cebu and in some parts of the Philippines is growing and I think this online language translator can help them learn about our Bisayan or Cebuano language.


Wednesday, July 23, 2008

JavaScript onClick Event


This is another "Hello World" example using JavaScript. The example below is a html script that is embedded with a javascript that will display a message in a messagebox whenever the button is clicked.

Your javascript must be placed inside the <head> </head> section of your html code. The javascript code must also be enclosed with the tag <script> </script>. Inside the <script> tag, you need to set the language property to "javascript".

The script is simple, we declare a new function called greet() and when this function is called, it will call a javascript built-in function called alert(). The alert function will pop-up a messagebox displaying the string "Hello! How are you today?".

Now that we have our javascript, we need to call the greet() function whenever a certain event is triggered. In this example, we added a button in our html code and set the onClick event of this button to call the function greet().

You try clicking the "Hello World" button below to see the output of this script.


The Script

<html>
<head>
<title>Yet another Hello World</title>
<script language="javascript">
function greet()
{
alert("Hello! How are you today?");
}
</script>
</head>
<body>
<form name="Form1">
<input type="button"
name="btnGreeter"
value="Hello World"
onclick="greet()" />
</form>
</body>
</html>


The Output





Thursday, May 8, 2008

Accepting Inputs in Python

I want to learn how to get or accept inputs in python. I want to start from the very basic. In C, there are several functions you can choose from, the very basic is scanf(). In python, there is this raw_input() function. The raw_input([prompt]) function will first display what is placed in [prompt] then wait for keyboard input(s) and return the input as a string.

Now, lets try this example:

#!/usr/bin/env python
# Filename: greeter.py
# Description: A program that ask for a name and greet hello.
# Author: Obispo

# Ask for a name.
iname = raw_input("What's your name? ")
# Be courteous
print "Oh, hello " + iname + "! Glad to meet you!"

Here is the output of our greeter.py code:

# ./greeter.py
What's your name? Juan
Oh, hello Juan! Glad to meet you!

We have to take note that raw_input() will return the input as a string. Let us take a look at our second example. Suppose I want to ask two numbers and display the sum of those numbers? Let us try:

#!/usr/bin/env python
# Filename: simplemath.py
# Description: A program that takes two numbers and display the sum
# Author: Obispo

# Ask for the first number
num1 = raw_input("Enter first number: ")
# Ask for the second number
num2 = raw_input("Enter second number: ")
# Alright, let's display the sum
print "The sum of ", num1, " and ", num2, " is ", (num1 + num2)

I wanna see the output now!

# chmod +x simplemath1.py
# ./simplemath1.py
Enter first number: 5
Enter second number: 3
The sum of 5 and 3 is 53

Oh, I don't think the answer is correct. What happened? As I have said, raw_input() will return a string, so, when we type 5 and 3, num1 and num2 contains the string "5" and "3" respectively. What about (num1 + num2)? Would it not automatically convert num1 and num2 into a numerical value then add? Well, from the output of the program, it didn't add num1 and num2 but instead, it concatenate the two strings "5" + "3" equals "53"!

You will notice that in our first example (greeter.py), we print our message like this: "Oh, hello " + "Juan" + "! Glad to meet you!". The "+" operator will be used to concatenate two strings if our operands are strings but it can also be used to add two values if our operands are numeric values.

In order to get the desired result, I used the function float() in order to convert the input "5" into a numeric value 5.0 and the input "3" into a numeric value 3.0. You can also try to use other numeric conversion functions like int() and long().

#!/usr/bin/env python
# Filename: simplemath.py
# Description: A program that takes two numbers and display the sum
# Author: Obispo

# Ask for the first number
num1 = float(raw_input("Enter first number: "))
# Ask for the second number
num2 = float(raw_input("Enter second number: "))
# Alright, let's display the sum
print "The sum of ", num1, " and ", num2, " is ", (num1 + num2)

Let's see the output:

# ./simplemath.py
Enter first number: 5
Enter second number: 3
The sum of 5.0 and 3.0 is 8.0

Whew! At last, the output seems to be correct now. What I want to learn next is how to trap errors in python, try to explore the program and you will see why.


Tuesday, May 6, 2008

Transferring Files using Shell Script

I have a directory where all my test codes are in there. I have test codes for C, shell scripts, perl and etc inside this directory. I realized that I could organize it further if I'll create a directory for c source codes, shell script source codes and etc. If I'll do the task manually, it will be a repetitive task. So I wrote a shell script to do the task for me.

#!/bin/sh
# Filename: organize.sh
# Description: A simple program that will transfer
# selected files to a certain directory
# Author: Obispo

# create a directory for c files
mkdir cfiles

# create a directory for sh files
mkdir shfiles

# transfer all c source codes to cfiles directory
for f in `ls *.c`
do
mv ${f} ./cfiles
done

# transfer all shell scripts to shfiles directory
for f in `ls *.sh`
do
mv ${f} ./shfiles
done

exit 0

Okay, here's how I came up with the program. If I'll execute the command 'ls *.c' at the console, it will display all the files that ends with '.c' right? So what I did was to get these files that ends with '.c' one by one and place it in a variable called 'f' then move it to my cfiles directory. The Unix command to move a file to another directory is 'mv'.


Friday, May 2, 2008

Counting Numbers in Shell Scripts

Scripts are very useful especially in automating repetitive task for system administration. Let me share to you a very simple shell script that will display numbers from 1 to 10 using while loop.

#!/bin/sh
# Filename: count.sh
# Description: Display numbers 1 to 10 using while loop
# Author: Obispo

# initialize a variable
i=1

# do the loop
while [ ${i} -le 10 ]
do
# you may place your repetitive task here
echo "count: ${i}"
i=`expr ${i} + 1`
done

exit 0


Output:
# ./count.sh
count: 1
count: 2
count: 3
count: 4
count: 5
count: 6
count: 7
count: 8
count: 9
count: 10


You're probably wondering whats the use of printing numbers 1 to 10 in the screen? I know how to that even when my eyes are closed. Well, all I can say is that you will need it someday when you grow up. :)


Thursday, May 1, 2008

Variables in Python 2

So, where am I now in my study of python? Ah! in my last post, I assigned numeric values to variables a, b and c. This time, I want to have a variable that contains a string, how am I going to do that?

Try this:

#!/usr/bin/env python
# Filename : stringvar.py
# Description : A simple example that shows how to assign a string to a variable
# Author : Obispo

str="Hello World!"
print "str = ", str

Output:

# ./stringvar.py
str = Hello World!

That's it! The code is so straight forward. Luckily python is not like any other programming language wherein you need to define the data type of your variable first before assigning value into it.


Wednesday, April 30, 2008

Variables in Python 1

Honestly, I got so excited learning Python after I discovered how to write the "Hello World!" program in Python. From my "Hello World!" program, I learned how to place comments in my program, in the beginning of your comment, you just got to place a sharp(#) to denote that the line is not part of the code, its only a comment.

Displaying a string in python was never hard at all, all I did was to call the instruction 'print' then preceded with the string I want to display which is of course the "Hello World!" string enclosed with a double-quote.

But wait! Is the first line of my code also a comment? I didn't know that writing a blog would make me feel like crazy. I got to answer my own questions! hehehe!

Here's the first line of the hello.py code:
#!/usr/bin/env python

That's the first line I was referring to. Hmmm... It looks like its also a comment right? This first line is very important in python programming. Just like Shell programming or Perl programming, this first line tells the my FreeBSD or the Unix box that the hello.py is to be executed with the python interpreter.

So much for the hello.py. In programming, it is very important that you know how to use variables. So this is my first program in python that shows you how to use variables:

#!/usr/bin/env python
# Filename: variables.py
# Description: A simple program that shows how to use variables in python
# Author: Obispo

# Lets declare a variable called a and assign it with a value equal to 1
a = 1

# Lets declare a variable called b and assign it with a value equal to 2
b = 2

# Lets declare a variable called c and assign it with a value equal to 3
c = 3

print "Variable a is ", a
print "Variable b is ", b
print "Variable c is ", c
print "Sum of a + b + c is ", a + b + c

Again, I used vi editor to type this code and saved it with a filename variables.py. I also made the program executable using the command 'chmod +x variables.py'. Excited to see the output of this code? Here's the output:

# ./variables.py
Variable a is 1
Variable b is 2
Variable c is 3
Sum of a + b + c is 6

That's it! Waaa... Those variables contains only numbers, how about having a variable that contains strings?

Hmm... I wanna learn that one too, but I've got no time to study and write anymore, it 11:21AM now and I have a lunch date with my wife. Got to go now, til next time...


Hello World in Python

I'm trying to study programming or scripting with Python and I remember when I first learned programming in C, I started with writing a "Hello World!" program.

Since this is my first time in python too, I want to convert my "Hello World!" program in C into Python and this is how it looks like:

#!/usr/bin/env python
# This is a comment in python
# Filename: hello.py
# Description: This program will display the very famous "Hello World!" in python
# Author: Obispo

print "Hello World!"

# The program ends here

I installed my python interpreter at my FreeBSD box and used the vi editor to write this code. I named the program "hello.py" and after saving it, I make it executable by changing the user permission of the file to executable. I used the command:
# chmod +x hello.py

Now that its executable, I got very excited to see the output. And so I run the program like this:
# ./hellopython.py
Hello World!


The "Hello World!" message did appear! Wow!
Digg