Thursday, October 7, 2010

C++ - Maps and Vectors

 I have been learning something really exciting this semester. It is a grad course called Object oriented software development using C++. Apart from learning the pillars of object orientation i.e. encapsulation, inheritance and polymorphism, I have got a chance to delve into game programming. It is a challenging domain and I will post some of my animation/game videos sometime soon.
The other day, I was writing some code to familiarize myself with vectors and maps. Here it goes -
#include <iostream>
#include
<map>
#include
<vector>
using std::string;
using std::cout;
using std::endl;
using std::vector;

//Todo: check how to use overloading for 'print' function
void print(std::map
<string,int> &m) {
  std::map
<string,int>::const_iterator it;
  for(it=m.begin();it!=m.end();++it) {
    std::cout << (it)->first << " = " << (it)->second << std::endl; 
  }
}
//Todo: check how to use overloading for 'print' function
void print(vector
<int> v) {
  vector
<int>::const_iterator it;
  for(it=v.begin();it!=v.end();++it) {
    std::cout<< (*it) << std::endl;
  }
}

void initializevec(vector
<int> &vec) {
  for (unsigned int i = 0 ; i < 20; ++i) {
    vec.push_back(i);
    //demonstrates how capacity grows as size of vector increases
    cout << "size = " << vec.size() << " capacity = " << vec.capacity() << endl;
  }
}

int main() {
  cout<< " MAP " << endl;
  std::map
<string,int> mymap;
  mymap["b"] = 1;
  mymap["a"] = 2;
  mymap["c"] = 5;
  mymap["d"] = 3;

  print(mymap);
  cout << "size = " << mymap.size() << endl;

  std::map
<string,int>::iterator it = mymap.find("c");
  cout<< "Deleting 'c' ... " <
  mymap.erase(it);
  print(mymap);
  cout << "size = " << mymap.size() << endl;   
  std::cout << std::endl;

  cout<< " VECTOR " << endl;
  vector
<int> vec;
  initializevec(vec);

  vec.push_back(13);
  print(vec);

  return 0;
}

Compile using -
g++ -W -Wall -Weffc++ -ggdb -O0 filename.cpp

It demonstrates some basic operations of maps and vectors. It was nice to understand how vectors increase their 'capacity' to accommodate new elements.

Friday, September 17, 2010

Yii - data grid view with some customization of cell content format

Lets start by creating a simple table

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(20) NOT NULL,
  `password` varchar(128) NOT NULL,
  `activationKey` varchar(128) NOT NULL DEFAULT '',
  `createtime` int(10) NOT NULL DEFAULT '0',
  `lastvisit` int(10) NOT NULL DEFAULT '0',
  `superuser` int(1) NOT NULL DEFAULT '0',
  `status` int(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`),
  KEY `status` (`status`),
  KEY `superuser` (`superuser`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

Configure the database connection as shown in one of the earlier posts.

Generate the corresponding model for the table in your database by executing the following commands
>protected\yiic shell

>> model *

Now, I want to create a data grid view to show the details of the table.

To show a link to the new "users" page(with a data grid) on navigation bar, open the file ..\mytestapp\protected\views\layouts\main.php

and add the following entry, in the "mainmenu" div.


widget('zii.widgets.CMenu',array(
            'items'=>array(
array('label'=>'Home', 'url'=>array('/site/index')),
array('label'=>'Users', 'url'=>array('/site/users')),  //####### new entry
array('label'=>'About', 'url'=>array('/site/page', 'view'=>'about')),
array('label'=>'Contact', 'url'=>array('/site/contact')),
array('label'=>'Login', 'url'=>array('/site/login'), 'visible'=>Yii::app()->user->isGuest),
array('label'=>'Logout ('.Yii::app()->user->name.')', 'url'=>array('/site/logout'), 'visible'=>!Yii::app()->user->isGuest)
),
)); ?>



The site controller needs information about where to render the new "users" page.
This can be done by adding the following method in the ..\mytestapp\protected\controllers\SiteController.php file

public function actionUsers()
    {
    $dataProvider=new CActiveDataProvider('Users');
    $this->render('users',array('dataProvider'=>$dataProvider,
                ));
    }

As you would notice that these methods should begin with "action" prefix.

Create a new file "users.php" at this location
..\mytestapp\protected\views\site\users.php

The contents of this file would look something like this-


$this->pageTitle=Yii::app()->name . ' - Users';
$this->breadcrumbs=array(
    'Users',
);

?><h1>Users

beginWidget('CActiveForm', array(
    'id'=>'members-form',
    'enableAjaxValidation'=>true,
)); ?>

widget('zii.widgets.grid.CGridView', array(
    'dataProvider'=>$dataProvider,
    'columns'=>array(
   array(
    'name'=>'id',
    'value'=>'CHtml::encode($data->id)'
   ),
   array(
    'name'=>'username',
    'value'=>'CHtml::encode($data->username)'
   ),
   array(
    'name'=>'createtime',
    'value'=>'CHtml::encode(date(\'Y-m-d\', $data->createtime))'  //this will format the unix timestamp to a custom date format
   ),
   array(
     'name'=>'lastvisit',              
     'value'=>'CHtml::encode(date(\'Y-m-d\', $data->lastvisit))'      // format the cell with date format
   ),
   array(
     'name'=>'status',
     'value'=>'CHtml::encode($data->status==1 ? \'Active\': \'Inactive\' )' 
// to render the gridview cell with a particular value
    ),
    ),
)); ?>
endWidget(); ?>


The page should be hosted at
http://localhost/mytestapp/index.php/site/users
or
http://localhost/mytestapp/index.php/?r=site/users

depending on the url manager setting in the config file.

Thursday, September 9, 2010

Setup and debug an Yii app in Netbeans IDE

After using Eclipse for a while I switched to Netbeans IDE for Yii development. It seems faster and easier to setup. Following is my experience of setting up the development environment.

Create a project stub using the following command -
>> yii-1.1.3.r2247\framework\yiic webapp mytestapp

Open Netbeans IDE and proceed with the following steps -
1. Click on File-> New Project
    This will open up a dialog box. Select "PHP" under "Categories" and under "Projects" select "PHP Applications with Existing Sources".


    Click Next.
2. In the "Sources Folder", input the path of "mytestapp" folder on your machine.
    Assign a project name. "mytestapp" for my case.
    Select a PHP version.
    Click Next
3. The options in this form should be set up automatically like below.
   

    Click Finish
   
    This should set up your Yii project in Netbeans IDE.
   
4. Go to "Debug" menu on the top bar on Netbeans IDE. Select "Debug Project(mytestapp)" and you should be able to debug your project.


5. "Continue(F5)" option in Debug can be used to resume a stopped debug session.
   

Tuesday, August 24, 2010

Yii - Authentication from mysql database using a md5 password

Before proceeding make sure the database has been connected to Yii application. (see previous post)
For this example, the passwords are stored in the database as md5 hash.
You may be required to change the password encoding scheme.

Edit the authenticate method in ../my_app/protected/components/UserIdentity.php to look like this -

public function authenticate()
    {
        //$users=array(
            // username => password
            //'demo'=>'demo',
            //'admin'=>'admin',
        //);
       
        $user = myUsersTable::model()->findByAttributes( array( 'my_userid_column_name' => $this->username));
        if ($user===null) { // No user was found!
            $this->errorCode=self::ERROR_USERNAME_INVALID;
        }
        // $user->Password refers to the "password" column name from the database
        else if($user->Password !== md5("my_salt1".$this->password))
        {   
            $this->errorCode=self::ERROR_PASSWORD_INVALID;
        }
        else { // User/pass match
            $this->errorCode=self::ERROR_NONE;
        }       
        return !$this->errorCode;
    }

Enter the username/password pair on the login page and you should be good to go.

Friday, August 6, 2010

A UNIX survival guide for students


1. Basic UNIX commands
    > ls
        List the contents in current directory.   
    > ls -alF
        List the contents in long format in the current directory.
       
    > cd directoryname
        Change current directory to another directory.
       
    > mkdir directoryname
        Create a directory.
       
    > cp file1.txt file2.txt
        Make a copy of file1.txt.
       
    > mv /home/harpreet/file1.txt /tmp/file2.txt
        Move the file to different location or can be used for renaming a file.
       
    > rm filename.txt
        Delete a file.
       
    > rm -R directoryname
        Delete the contents of a directory.
       
    > head -20 filename.txt
        Get 20 lines from the top of the file.
       
    > tail -30 filename.txt
        Get 30 lines from the bottom of the file.
   
2. vi filename.txt
    Edit a file.
    a. Esc dd
        Deletes the current line
    b. Esc u
        Undo the last action
    c. Esc :0       (zero)
        Move cursor to first line of file
    d. Esc $
        Move to end of current line
    e. Esc Shift+g
        Move to end of file
    f. Esc yy
        Copy the current line
        Esc y3y
        Copy the next three lines
    g. Esc p
        Paste the copied line(s)
    h. Esc :35
        Moves the cursor to line number 35
    i. Esc /wordtofind
        Find the word within the file. Press 'n' to move to the next occurrence.
       
3. > grep 'wordtofind' filename.txt
        Finds the line containing a string from the file
       grep -i 'wordtofind' filename.txt
        Case-insensitive find.

4. > find /tmp/directoryname -name test.txt
        Find a file with name 'test.txt' in the given path.

5. > find . -type f -exec grep -i Row2 {} \; -print
        Find the word 'row2' from all the files in current path.
        Also, shows the line containing an occurrence of the word.
   
6. > scp harpreet@hostname.edu:/tmp/file.txt .
        Copy a file located on another server to the current directory on the present server.
   
    > scp file.txt harpreet@hostname.edu:.
        Copy a file from current server to another server into your home directory.
   
    > scp file.txt harpreet@hostname.edu:/home/directory/file.txt
        Copy a file from one machine to another.   
   
7. > tar cvzf new_tar_file.tar.gz file1.txt file2.txt
        Create a tar file new_tar_file.tar.gz containing file1.txt and file2.txt
   
    > tar xvzf abc.tar.gz
        Untar the contents of a file abc.tar.gz to the current directory
   
8. awk - Let us create a file 'test.txt' with these contents
       Row1-column1 Row1-column2 Row1-column3 Row1-column4
   Row2-column1 Row2-column2-HARPREET Row2-column3 Row2-column4
   Row3-column1 Row3-column2 Row3-column3 Row3-column4-SINGH
       
    Observe the output for various commands
    >  awk '{print $2}' test.txt
      Row1-column2
    Row2-column2-HARPREET
    Row3-column2
        The above command prints the second column
       
    String matching using awk :
    >  awk '{if ( $4 ~ /SINGH/ ) { print $2 $3}}' test.txt
    Row3-column2Row3-column3
        The above command matches the string 'SINGH' and prints column 2 and 3.   

Corrections/improvements/questions are welcome :)

Friday, July 30, 2010

Compiling Ganglia - Errors and problems

Some errors and problems:


My install directory was /opt/ganglia.


Error -
checking for gcc... no
checking for cc... no
checking for cl.exe... no
configure: error: no acceptable C compiler found in $PATH
See `config.log' for more details.

Solution -
Add gcc bin path to PATH environment variable



Error -
checking for pcre.h... no
checking for pcre_compile in -lpcre... no
libpcre not found, specify --with-libpcre=no to build without PCRE support

Solution -
PCRE is not installed.
# wget ftp://ftp.sunfreeware.com/pub/freeware/SOURCES/pcre-8.10.tar.gz
# /usr/local/bin/tar -xzf pcre-8.10.tar.gz
# cd pcre-8.10
# ./configure --prefix=/opt/ganglia
# make && make install

Make sure you add, -I/opt/ganglia/include to CFLAGS environment variable
and -L/opt/ganglia/lib to LDFLAGS after this.



Problem -
Graphs not shown in ganglia or images not shown on ganglia front end.


Reason -
php-gd may not have been installed.
You can do so by ( as root) -
# yum install php-gd
Another reason could be front-end can't find RRD path. Make sure it is set in conf.php


Error -
checking for apr-1-config... no
configure: error: apr-1-config binary not found in path


Reason -
APR is not installed or path of apr-1-config is not available through the PATH environment variable.


Error -
libgcc_s.so.1: open failed: No such file or directory


Solution-
Execute the following:
# ldd gmond
...
libgcc_s.so.1 => (file not found)
...


So gmond can link to libgcc


Add the following to you LDFLAGS
# setenv LDFLAGS $LDFLAGS:-R/yourgccpath/gcc-4.0.3/lib


-R records the runtime search path.


Install again
# ./configure --prefix=/opt/ganglia --sysconfdir=/opt/ganglia/etc
# make && make install


Error -
After installation, while executing gmond
apr_pollset_create failed: Invalid argument

Solution -
In your config file gmond.conf, if there is no udp_recv_channel or tcp_accept_channel
defined, gmond fails to run with this error.
Set "deaf = yes " under "globals"

Error -
/usr/bin/ld: cannot find -lpython2.3
collect2: ld returned 1 exit status
make[4]: *** [modpython.la] Error 1

Solution -
I dont remember exactly how i resolved it.
Most likely it was the linker not being able to find python.
Probably by setting library flags this error was resolved.

Error -
false cru libgetopthelper.a getopt1.o getopt.o getopt_init.o
make[2]: *** [libgetopthelper.a] Error 1

Solution -
Add /usr/ccs/bin to PATH environment variable.

In case of dependency not found errors, you could configure options, like --with-libapr, --with-libconfuse to point to dependency paths.

Error -
Some gm_protocol_xdr.c related warnings and finally build fails with this error

ld: fatal: relocations remain against allocatable but non-writable sections
collect2: ld returned 1 exit status

Solution -
Uninstall the dependency 'confuse' and install it by setting CFLAGS="-O3 -fPIC"
> cd ../confuse-2.7/
> make uninstall
> make clean
> env CFLAGS="-O3 -fPIC" ./configure --prefix=/opt/ganglia
> make && make install

Do a configure, make and make install and you should be good.
 

jQuery - Start date/end date datepicker calendar and datatable

This post is basically a snippet of code to address the following -
1. Attach jQuery (datepicker) calendar to start date and end date inputs.
2. Create a jQuery datatable
3. On page submit, hide submit button and show a loading image instead.

After you have downloaded jQuery and extracted it to appropriate folders,
create a php file with these contents -

<?php
 
class InitPage {
    public $jscript = "
    <script type=\"text/javascript\" src=\"js/jquery-1.4.2.min.js\"></script>
    <script type=\"text/javascript\" src=\"ui/jquery.ui.core.js\"></script>
    <script type=\"text/javascript\" src=\"ui/jquery.ui.widget.js\"></script>
    <script type=\"text/javascript\" src=\"ui/jquery.ui.datepicker.js\"></script>       
    <script type=\"text/javascript\" src=\"js/jquery.dataTables.js\"></script>
    <script type=\"text/javascript\" src=\"js/myjscript.js\"></script>";

    public $css =
        " <link type=\"text/css\" href=\"themes/redmond/jquery.ui.all.css\" rel=\"stylesheet\" />";       
    public $header = "<html><head><title>Random Information</title>";   
    public $body = "</head><body ><h1 >Random Information</h1>";           
    public $footer =
        "<div id=\"footer\"><p><a href=\"http://rowsandcolumns.blogspot.com\">
        http://rowsandcolumns.blogspot.com</a></div></body> </html>";                       
    public function print_page($v_header,$v_jscript,$contents,$v_footer="") {
        if(!$v_header) {
            $v_header = $this->header.$this->jscript.$this->css.$this->body;
        }
        if(!$v_footer) {
            $v_footer = $this->footer;
        }
        echo $v_header.$contents.$v_footer;
    }   
    function is_date( $str )
    {
      $stamp = strtotime( $str );
      if (!is_numeric($stamp)) {
         return FALSE;
      }
      $month = date( 'm', $stamp );
      $day   = date( 'd', $stamp );
      $year  = date( 'Y', $stamp );     
      if (checkdate($month, $day, $year)) {
         return TRUE;
      }     
      return FALSE;
    }    
}

$table_contents = "";

if(isset($_POST) && !empty($_POST)) { //On submit enter here
$bp = new InitPage();
// Get dates and validate if
//start date and end date are in proper format
    if (isset($_POST["start-date"]) &&
                $bp->is_date($_POST["start-date"]) &&
                    isset($_POST["end-date"]) &&
                        $bp->is_date($_POST["end-date"])
        ){
   
    list($start_date_m, $start_date_d, $start_date_Y)= explode("/",$_POST["start-date"]);
    list($end_date_m, $end_date_d, $end_date_Y)= explode("/",$_POST["end-date"]);
   
    $start_date = date("Y-m-d H:i:s", mktime(8, 0, 0, $start_date_m, $start_date_d, $start_date_Y));
   
    $end_date = date("Y-m-d H:i:s", mktime(8, 0, 0, $end_date_m, $end_date_d, $end_date_Y));
    if($end_date <= $start_date) {
        $table_contents.= "<font size=\"2\" color=\"red\">Start date should be
                            less than end date!</font>";
        $bp->print_page("","",$table_contents,"");
        die;
    }   
    //Time to hide submit button and show loading image
    sleep(3);
    $table_contents = "<br/><br/><div style=\"width:500;\" >
    <table border=\"1\" width=\"500\" id=\"reading\">
    <thead>
        <tr>
            <th>Serial #</th>
            <th>Name</th>
            <th>Count</th>
        </tr>
    </thead>
    <tbody>
    <tr><td> 1 </td> <td> Managers </td> <td> 10 </td></tr>
    <tr><td> 2 </td> <td> Engineers </td> <td> 50 </td></tr>
    <tr><td> 3 </td> <td> Interns </td> <td> 5 </td></tr>
    <tr><td> 4 </td> <td> Executives </td> <td> 3 </td></tr>
    <tr><td> 5 </td> <td> Facilities </td> <td> 2 </td></tr>
    </tbody>
    <tfoot>
    <tr>
            <th>Serial #</th>
            <th>Name</th>
            <th>Count</th>           
    </tr>
    </tfoot>
    </table></div><br/>    ";
    }
    else {
        $table_contents.= "<font size=\"2\" color=\"red\">Start date/End date
                            is not valid!</font>";
    }
    $bp->print_page("","",$table_contents,"");
    die;
}
else { // On first page load
$bp = new InitPage();
$select_cb = "<form action=\"index.php\" method=\"post\">Please select start and
        end date...<br/>
        <br/><label for=\"start-date\">Start date:</label>
        <input type=\"text\" name=\"start-date\" id=\"start-date\"/><br/><br/>
        <label for=\"end-date\">End date: </label>
        <input type=\"text\" name=\"end-date\" id=\"end-date\"/>

        <p><input type=\"submit\" id=\"submit_button\" name=\"submit_button\"
                value=\"Submit\"></p>
        <span id=\"spanloader\" style=\"display: none;\"><img src=\"images/loading1.gif\"
            alt=\"Please wait...\"> Please wait...</span> 
        </form> ";
$bp->print_page("","",$select_cb,"");
}
?>

Create javascript file (js/myscript.js) with these contents:
  
//attach datepicker to start date
$(function() {
    $("#start-date").datepicker();
});
//attach datepicker to end date   
$(function() {
    $("#end-date").datepicker();
});
   
$().ready(function() { 
    $('#submit_button').show(); 
     
//hide the submit button after click and show loading image 
        $('[id$=submit_button]').click(function() { 
                $('#spanloader').show(); 
                $('#submit_button').hide();  
            }); 
}); 
   
//set datatable   
$(document).ready(function() {
    $('#reading').dataTable({
    "bJQueryUI": true,   
    "sPaginationType": "full_numbers"});
} );

This should get you started with a data table and start date end date datepicker using jquery.