Thursday, June 14, 2012

Shell Profile Reload

For those of you, who are familiar with shell in Linux or Unix environment, the file .bash_profile (or .profile in Mac OS X) must already be familiar. This file is used to store initialisation commands to be used for the entire shell session. Example of things you can put into this file is putting alias for commands and registering environment variables.

As the .bash_profile and .profile are just regular files, we can change it at any time. However, it will be quite a hassle if every time we change the file we need to close and open a new shell window. There is a command that we can use to re-run the profile file on the fly. Following is the full command you can use to do that.

Under Linux
source ~/.bash_profile

Under Mac OS X
source ~/.profile
Hope this helps you. Have fun.

Sunday, May 20, 2012

Public Key Infrastructure Fundamental (Part 2)

This post is a continuation (par 2) of my post that can be found here. In this post, I am going to discuss about Public Key and Private Key.



Public Key

Public key can be defined as a value provided by some designated authority as an encryption key that, combined with a private key derived from the public key, can be used to effectively encrypt messages and digital signatures. Private key will be discussed below.


Private Key

Private key can be defined as an encryption/decryption key known only to the party or parties that exchange secret messages.

Public-key Encryption
Source: Globus
As you can see from the above image, the public-key and private-key are both used in the encryption process in the PKI. One think you need to remember, we use the receiver's public-key as the key to encrypt the message. On the other side, the receiver, will decrypt the message using the private-key that he has.

To simplify things:
  • Think of a public key as being the lock. It’s not actually a key, it’s a padlock you can make lots of copies of and distribute wherever you want.
  • Think of a private key as being the actual key. This is what you use to open the padlock that is stored on the other machine. Just like a regular key you keep it secret, safe, and out of the wrong hands.

Public-key Encryption
Source: Wikimedia

In an asymmetric key encryption scheme, anyone can encrypt messages using the public key, but only the holder of the paired private key can decrypt. Security depends on the secrecy of that private key.

Thursday, May 17, 2012

Simple Paging

Paging literally means making data displayed in multiple pages. Paging is used specially for website, where displaying large amount of data can be so troublesome by making the downloaded data bigger and thus increasing the response time.

Paging can be done in many ways. In this tutorial, I would like to show you a very simple method we can use to do the paging. Here, we just need to enable the user to move to the next page (if any) and back to the previous page (if any). Also, for the sake of simplicity, I will use dummy data stored hard-codedly into an array. However, the concept is similar. OK, let's start !!!

    /* Maximum number of items to show, per page */
    $maxItemPerPage = 10 ;
    
    /* 
     * Prepare the dummy data
     * Used just for the sake of this tutorial.
     */
    $data = array ( ) ;

    for ( $i = 1 ; $i <= 112 ; $i ++ )
        array_push( $data , "Item " . $i ) ;
First of all, we define the maximum number of items to show per page. In this tutorial, I set the maximum number of items to show per page to 10 items. This value can be changed according to your need. However, sometimes, this value can also be changed by users as to accommodate his preferences. Sometimes, users' screen is big enough to show large count of data per page. After that, I created dummy data. Please not that in reality, mostly data stored in the database.

    /* 
     * Create function to retrieve the data.
     * 
     * The content of this function must be changed
     * according to the neccessity and logic of your
     * application regarding the data retrieval process.
     */
    function retrieveData ( $pageNumber )
    {
        global $data ;
        global $maxItemPerPage ;
        
        /* page the data */
        /* Prepares the variable used to store paged data */
        $result = array ( ) ;
        
        /* Calculate the data count */
        $dataCount = count ( $data ) ;
        
        /* Calculate the offset. Offset literally means from what index should we start retrieving the data */
        $offset = ( $pageNumber - 1 ) * $maxItemPerPage ;
        
        /* Calculate the maximum index we can use to retrieve the data */
        $limit = $offset + $maxItemPerPage ;
        
        /* Check if the limit is more than the number of data we have, just set the limit to the data count */
        if ( $limit > $dataCount )
            $limit = $dataCount ;
        
        /* Store the data now */
        for ( $i = $offset ; $i < $limit ; $i ++ )
            array_push ( $result , $data [ $i ] ) ;
        
        /* Return the paging result */
        return $result ;
    }
The next step, I created a helper function to ease the retrieval of data. All the retrieval data logic put into that function. Also note that the content of that function must be changed according to the way you retrieve the data. If you use SQL to retrieve the data, you can use the SQL Query to do the paging automatically. Here, I will show you an example of how to filter data retrieved using MySQL SQL command. Please refer to your DBMS documentation for command supported in your own DBMS.
SELECT <columns> FROM <table> LIMIT <limit>, <offset>

    /* Get the page number from query string */
    $page = $_GET [ "p" ] ;
    
    /* If not "p" (page) given, then assume the requested is page 1 */
    if ( ! isset ( $page ) )
        $page = 1 ;
    
    /* Calculate max page number */
    $maxPageNumber = ceil ( count ( $data ) / $maxItemPerPage ) ;    
    $paged_data = retrieveData ( $page ) ;
One part we need to handle is to get the requested page number sent by the user. We can easily pass it using query string passed into the server. Note that, for security sake, you should always check for the validity of values passed by the user, in case they want to inject something bad into your server by using the weakness or security hole you created unintentionally by your bad code. For this tutorial, I omit that checking.

As you can see, I use "p" variable that is sent to server using HTTP GET method to store the requested page number. If, the "p" variable is empty, I assume that the user is requesting data in the first page. So, all required data is ready, I now just need to display the data to the user.
    /* Print the data */
    echo "<table style=\"width: 100%\" border=\"1\"><tr><th style=\"background-color: #00FFAA\">Items</th></tr>" ;
    
    /* Loop through the paged-data */
    foreach ( $paged_data as $item )
        echo "<tr><td style=\"background-color: #EEEEEE\">$item</td></tr>" ;
    
    /* Print the prev/next page link */
    if ( $maxPageNumber > 1 )
    {
        echo "<tr><td style=\"background-color: #00FFFF; text-align: center\">" ;
        
        /* We can go backward to previous page since the minimum page is 1 and we are currently not at page 1 */
        if ( $page > 1 )
            echo "<a href=?p=" . ( $page - 1 ) . ">Prev. Page</a>  " ;
        
        /* We can go forward to the next page since the current page is still less than the maximum page */
        if ( $page < $maxPageNumber )
            echo "<a href=?p=" . ( $page + 1 ) . ">Next Page</a>" ;
        
        echo "</td></tr>" ;
    }
        
    echo "</table>" ;
?>
I think the printing process is very common. I don't really need to explain it a bit deeper, I suppose. The logic you need to have a look is actually the checking whether we need to display the "Prev. Page" link and "Next Page" link or not. The inline documentation should explain better. See below for the full source code.
<?php
    /* Maximum number of items to show, per page */
    $maxItemPerPage = 10 ;
    
    /* 
     * Prepare the dummy data
     * Used just for the sake of this tutorial.
     */
    $data = array ( ) ;

    for ( $i = 1 ; $i <= 112 ; $i ++ )
        array_push( $data , "Item " . $i ) ;
    
    /* 
     * Create function to retrieve the data.
     * 
     * The content of this function must be changed
     * according to the neccessity and logic of your
     * application regarding the data retrieval process.
     */
    function retrieveData ( $pageNumber )
    {
        global $data ;
        global $maxItemPerPage ;
        
        /* page the data */
        /* Prepares the variable used to store paged data */
        $result = array ( ) ;
        
        /* Calculate the data count */
        $dataCount = count ( $data ) ;
        
        /* Calculate the offset. Offset literally means from what index should we start retrieving the data */
        $offset = ( $pageNumber - 1 ) * $maxItemPerPage ;
        
        /* Calculate the maximum index we can use to retrieve the data */
        $limit = $offset + $maxItemPerPage ;
        
        /* Check if the limit is more than the number of data we have, just set the limit to the data count */
        if ( $limit > $dataCount )
            $limit = $dataCount ;
        
        /* Store the data now */
        for ( $i = $offset ; $i < $limit ; $i ++ )
            array_push ( $result , $data [ $i ] ) ;
        
        /* Return the paging result */
        return $result ;
    }
        
    /* Get the page number from query string */
    $page = $_GET [ "p" ] ;
    
    /* If not "p" (page) given, then assume the requested is page 1 */
    if ( ! isset ( $page ) )
        $page = 1 ;
    
    /* Calculate max page number */
    $maxPageNumber = ceil ( count ( $data ) / $maxItemPerPage ) ;    
    $paged_data = retrieveData ( $page ) ;
    
    /* Print the data */
    echo "<table style=\"width: 100%\" border=\"1\"><tr><th style=\"background-color: #00FFAA\">Items</th></tr>" ;
    
    /* Loop through the paged-data */
    foreach ( $paged_data as $item )
        echo "<tr><td style=\"background-color: #EEEEEE\">$item</td></tr>" ;
    
    /* Print the prev/next page link */
    if ( $maxPageNumber > 1 )
    {
        echo "<tr><td style=\"background-color: #00FFFF; text-align: center\">" ;
        
        /* We can go backward to previous page */
        if ( $page > 1 )
            echo "<a href=?p=" . ( $page - 1 ) . ">Prev. Page</a>  " ;
        
        /* We can go forward to the next page */
        if ( $page < $maxPageNumber )
            echo "<a href=?p=" . ( $page + 1 ) . ">Next Page</a>" ;
        
        echo "</td></tr>" ;
    }
        
    echo "</table>" ;
?>


That's it. Hope you enjoy the tutorial and can gain benefit from it. Remember, this is a very simple one. You can also use another way to do paging by enabling user to go to certain page directly. Or, if you are a professional programmer wannabe, don't worry, there are many frameworks out there that handle all the nifty-gritty in doing beautiful paging mechanism.

Happy code fellas....

Tuesday, May 1, 2012

Faster Prime Number Checker Algorithm

Checking for prime number is actually a simple one, but can sometimes be very tricky for big number. Though there exists more powerful algorithm to check for prime number, here I want to show you one simple algorithm that is proved to be fast enough.


//
//  main.cpp
//  Prime Number Checker
//
//  Created by Handra on 5/1/12.
//  Copyright (c) 2012 Handra. All rights reserved.
//

#include <iostream>
#include <cmath>

using namespace std ;

/* Function prototype */
int isPrime ( int number ) ;

int main ( int argc , const char * argv [ ] )
{
    int number = 12 ;
    
    cout << "Is Prime: " << isPrime ( number ) << endl ;
    
    return 0 ;
}

int isPrime ( int number )
{
    /* Every number below 2 is not prime */
    if ( number < 2 )
        return 0 ;
    
    /* Calculating the limit for denominator */
    int limit = ( int ) sqrt ( number ) ;
    
    /* Start the denominator from 2. We know that every number divided by 1 must have 0 carrier */
    for ( int i = 2 ; i <= limit ; i ++ )
        if ( number % i == 0 )
            return 0 ;
    
    return 1 ;
}

The above code is written using C++. Of course you can implement it using any other programming language.


So, as you can see within the function "isPrime", we first check whether the number is less than 2 or not. We know, by common sense and definition, that numbers below 2 are not considered as prime. Hence, we check that if the number is less that 2, then return 0, or false.


If the number is 2 or higher, then we need to check for it's primeness. First of all, we need to calculate the limit of the number we should use to divide the to-check-for-primeness-number. From the mathematical theorem, we know that the maximum factor value, that is not the same with the number, is the square root of the number. Proving of this theorem is beyond this post though. In C++, we use function sqrt that is defined in header cmath.


After that, the rest we need to do is loop starting from 2 to the limit to check whether there is another factor (besides 1 and the number itself). If any is found, then just return 0 (false) since there should be no other factor within 2 and the limit (inclusive). Otherwise, return 1 (true).


Hope this helps and happy coding.. :)

Tuesday, April 17, 2012

Einstein vs Professor

This story is retrieved from the Internet. Though the authenticity of this conversation is still in question, it's still worth it to read. Enjoy.

Professor : You are a Christian, aren’t you, son ?
Student : Yes, sir.
Professor: So, you believe in GOD ?
Student : Absolutely, sir.
Professor : Is GOD good ?
Student : Sure.
Professor: Is GOD all powerful ?
Student : Yes.
Professor: My brother died of cancer even though he prayed to GOD to heal him. Most of us would attempt to help others who are ill. But GOD didn’t. How is this GOD good then? Hmm?

(Student was silent.)

Professor: You can’t answer, can you ? Let’s start again, young fella. Is GOD good?
Student : Yes.
Professor: Is satan good ?
Student : No.
Professor: Where does satan come from ?
Student : From … GOD …
Professor: That’s right. Tell me son, is there evil in this world?
Student : Yes.
Professor: Evil is everywhere, isn’t it ? And GOD did make everything. Correct?
Student : Yes.
Professor: So who created evil ?

(Student did not answer.)

Professor: Is there sickness? Immorality? Hatred? Ugliness? All these terrible things exist in the world, don’t they?
Student : Yes, sir.
Professor: So, who created them ?

(Student had no answer.)

Professor: Science says you have 5 Senses you use to identify and observe the world around you. Tell me, son, have you ever seen GOD?
Student : No, sir.
Professor: Tell us if you have ever heard your GOD?
Student : No , sir.
Professor: Have you ever felt your GOD, tasted your GOD, smelt your GOD? Have you ever had any sensory perception of GOD for that matter?
Student : No, sir. I’m afraid I haven’t.
Professor: Yet you still believe in Him?
Student : Yes.
Professor : According to Empirical, Testable, Demonstrable Protocol, Science says your GOD doesn’t exist. What do you say to that, son?
Student : Nothing. I only have my faith.
Professor: Yes, faith. And that is the problem Science has.
Student : Professor, is there such a thing as heat?
Professor: Yes.
Student : And is there such a thing as cold?
Professor: Yes.
Student : No, sir. There isn’t.

(The lecture theater became very quiet with this turn of events.)

Student : Sir, you can have lots of heat, even more heat, superheat, mega heat, white heat, a little heat or no heat. But we don’t have anything called cold. We can hit 458 degrees below zero which is no heat, but we can’t go any further after that. There is no such thing as cold. Cold is only a word we use to describe the absence of heat. We cannot measure cold. Heat is energy. Cold is not the opposite of heat, sir, just the absence of it.

(There was pin-drop silence in the lecture theater.)

Student : What about darkness, Professor? Is there such a thing as darkness?
Professor: Yes. What is night if there isn’t darkness?
Student : You’re wrong again, sir. Darkness is the absence of something. You can have low light, normal light, bright light, flashing light. But if you have no light constantly, you have nothing and its called darkness, isn’t it? In reality, darkness isn’t. If it is, well you would be able to make darkness darker, wouldn’t you?
Professor: So what is the point you are making, young man ?
Student : Sir, my point is your philosophical premise is flawed.
Professor: Flawed ? Can you explain how?
Student : Sir, you are working on the premise of duality. You argue there is life and then there is death, a good GOD and a bad GOD. You are viewing the concept of GOD as something finite, something we can measure. Sir, Science can’t even explain a thought. It uses electricity and magnetism, but has never seen, much less fully understood either one. To view death as the opposite of life is to be ignorant of the fact that death cannot exist as a substantive thing.

Death is not the opposite of life: just the absence of it. Now tell me, Professor, do you teach your students that they evolved from a monkey?

Professor: If you are referring to the natural evolutionary process, yes, of course, I do.
Student : Have you ever observed evolution with your own eyes, sir?

(The Professor shook his head with a smile, beginning to realize where the argument was going.)

Student : Since no one has ever observed the process of evolution at work and cannot even prove that this process is an on-going endeavor. Are you not teaching your opinion, sir? Are you not a scientist but a preacher?

(The class was in uproar.)

Student : Is there anyone in the class who has ever seen the Professor’s brain?

(The class broke out into laughter. )

Student : Is there anyone here who has ever heard the Professor’s brain, felt it, touched or smelt it? No one appears to have done so. So, according to the established Rules of Empirical, Stable, Demonstrable Protocol, Science says that you have no brain, sir. With all due respect, sir, how do we then trust your lectures, sir?

(The room was silent. The Professor stared at the student, his face unfathomable.)

Professor: I guess you’ll have to take them on faith, son.
Student : That is it sir … Exactly ! The link between man & GOD is FAITH. That is all that keeps things alive and moving.

P.S.

I believe you have enjoyed the conversation. And if so, you’ll probably want your friends / colleagues to enjoy the same, won’t you?

Forward this to increase their knowledge … or FAITH.

By the way, that student was EINSTEIN.