Monday, 27 April 2015

Top 10 Paint Applications in UBUNTU

Update 1: Three more applications were added to the list, Tux Paint, Pinta and GrafX2.

Update 2: If you are interested in full-fledged, powerful image manipulation tools, have a look at GIMPKrita (on Steam too) and PaintSupreme. For photo albums and collections have a look at digiKamFotoxx or Shutter.
Kolourpaint
Kolourpaint is a feature-rich painting program for KDE with a typical user-friendly interface, supporting many image formats (including PNG, JPG, TGA, PNM, GIF, BMP, XPM or TIFF). It allows zooming in/out, copy/paste, printing, cropping, rotating, applying various effects (balance, emboss, soften & sharpen). I think it is a perfect application for making simple paintings or sketches.
sudo apt-get install kolourpaint4
MyPaint
MyPaint offers many features and also an interface which is somewhat unusual among painting applications. There is the actual workspace and a separate window with predefined brushes to select from. It features usual functions, including undo/redo, zooming in/out, many brush types, several effects. Two noteworthy things to mention here are the existence of layers and also the brush editor, which allows you to create your own brushes.
sudo apt-get install mypaint
mtPaint
This application is full-fledged, and comes by default with a black background. It offers application-specific settings (like showing/hiding toolbars, splitting window), and also various effects, channels, or layers. Although it’s pretty good and has many options, I doubt it’s a good match for kids.
sudo apt-get install mtpaint
Gnome-paint
This is a very simple drawing application for the GNOME desktop with a typical interface and few options. It offers basic functions and two sidebars: one to choose the tool to use and the other one to choose the color. The feature to insert text is not yet implemented.
sudo apt-get install gnome-paint
Gpaint
Gpaint is yet another simple painting program from GNU, built with GTK, which offers standard functions and quite a few effects, like sharpen, emboss, oil paint or solarize. There is no undo function.
sudo apt-get install gpaint
Tkpaint
Tkpaint is written in Tcl/Tk and offers predefined shapes, various line types, text inserting support and several other tools. It can open GIF, PPM or BMP formats and will save the output image as Encapsulated PostScript or Tcl script.
sudo apt-get install tkpaint
XPaint
XPaint is rather a nice painting application, including a C script editor, toolbox, brush selector, font selector, color and pattern editor, and even a magnifier.
sudo apt-get install xpaint
Addition: Tux Paint
Tux Paint is especially designed for kids, and it provides bulleted buttons for the usual painting tools and brushes. The very nice thing about Tux Paint is that it provides various sounds when the paint tools are used or selected.
sudo apt-get install tuxpaint
Pinta
Pinta is yet another powerful application for GNOME, featuring zoom in/out, fullscreen mode, rotate, resize, brightness/contrast and hue/saturation settings, brushes and the typical painting tools. Except for those, Pinta also offers various effects and layers.
sudo apt-get install pinta
GrafX2
Finally, there is GrafX2, which is a bitmap painting program for X, specialized in 256-color drawing. It is not suitable for children since it is a per-pixel drawing program and the interface may be a bit hard to get a handle on at first.
grafx2
sudo apt-get install grafx2
Rassam-paint
Rassam-paint is a simple painting program written using GTK2 with basic tools such as pencil, brush or flood fill, shapes (line, rectangle, ellipse) and support for all the popular formats out there (PNG, JPG, TIFF, ICO etc).
rassam_paint_03

Install Rassam-paint 1.1 in Ubuntu 14.04, Ubuntu 14.10 and Mint 17

DEB packages are available for both 32-bit and 64-bit systems, as well as pre-compiled binaries. To install Rassam-paint in Ubuntu or Mint you can download the DEB file for your architecture (32-bit or 64-bit) and either double click it or open a terminal and type the command below:
For 64-bit, download the DEB from here and to install it type:
sudo dpkg -i rassam-paint_1.0_amd64.deb
For 32-bit, download the DEB from here and to install it type:
sudo dpkg -i rassam-paint_1.0_i386.deb
The program will be installed as /usr/bin/rassam-paint.
The alternative would be to download the archive which contains the pre-compiled binary, then uncompress it, then run the program. The archive is decompressed in the current directory unless specified otherwise, with no root directory. The unzip package will need to be installed as well (sudo apt-get install unzip).
For 64-bit download the archive from here and type in a terminal:
unzip Rassam-paint_64bit_1.0.zip
./rassam-paint
For 32-bit download the archive from here and type in a terminal:
unzip Rassam-paint_32bit_1.0.zip
./rassam-paint

check boxes , Radio buttons and user defined labels in YII

We can define style to the check boxes by inserting the below <script> code in <head> section of the view page:

<style>
input[type=checkbox]
    {
        /* Double-sized Checkboxes */
        -ms-transform: scale(2); /* IE */
        -moz-transform: scale(2); /* FF */
        -webkit-transform: scale(2); /* Safari and Chrome */
        -o-transform: scale(2); /* Opera */
        padding: 10px;
    }
    input.big {          
        font-size: 110%;
        display: inline;
    }
</style>


The declaration of check boxes and buttons in VIEW is

<?php echo CHtml::label("i) Registered Document", ''); ?>  /* Here the label is defined differently, if we define this way we have flexibility to change color text etc */

for example, CHtml::label("Details of DD in token of advanced payment<font color='red'> * </font>", '') 


<?php echo $form->checkBox($model,'married',array('value' => 'Y', 'uncheckValue'=>'N'),array('labelOptions'=>array('style'=>'display:inline'))); ?>

The above one is the check box, with field name 'married' if the field checked the value of married will be 'Y' otherwise 'N'.

Lets see some more examples

<?php echo $form->checkBox($model,'proof_sd',array('value' => 'Y', 'uncheckValue'=>'N'),array('labelOptions'=>array('style'=>'display:inline'))); ?>
<?php echo $form->checkBox($model,'proof_pt',array('value' => 'Y', 'uncheckValue'=>'N'),array('labelOptions'=>array('style'=>'display:inline'))); ?>
<?php echo $form->checkBox($model,'proof_eb',array('value' => 'Y', 'uncheckValue'=>'N'),array('labelOptions'=>array('style'=>'display:inline'))); ?>
<?php echo $form->checkBox($model,'proof_wb',array('value' => 'Y', 'uncheckValue'=>'N'),array('labelOptions'=>array('style'=>'display:inline'))); ?>
<?php echo $form->checkBox($model,'proof_bc',array('value' => 'Y', 'uncheckValue'=>'N'),array('labelOptions'=>array('style'=>'display:inline'))); ?>

The above code gives the following view image





coming to RADIO BUTTONS

We can declare them using

<?php echo CHtml::label("Land Area covered ", ''); ?>

<?php echo $form->textField($model,'area',array('size'=>10,'maxlength'=>10)); ?>

<?php echo $form->radioButtonList($model, 'areaunits', array('sqyd'=>'Sq. Yds','sqft'=>'Sq. Fts',  'sqmt'=>'Sq. Mts'),array('labelOptions'=>array('style'=>'display:inline; margin-right: 10px; font-weight: bold;'), 'separator'=>'&nbsp;&nbsp;',)); 
?>

Here the radio button linked to areaunits of model, so we have given the fieldname it may consists of values sqyd or sqft or sqmt. The area is entered in textbox and units to be selected by the user using the radio button. Here the units are either of the feet or yards or meters.

'sqyd' => 'Sq.Yds' means 'value'=>'label' the displayed text is Sq.Yds where are value sqyd is stored in the backend.


The above view is displayed.

another examples are,
<?php echo $form->radioButtonList($model, 'chklist', array('Y'=>'YES', 'N'=>'NO')
,array('labelOptions'=>array('style'=>'display:inline; margin-right: 10px; font-weight: bold;'),
    'separator'=>'&nbsp;&nbsp;',
)); ?>

That's it

we can use the check boxes, radio buttons as above way , There is no more code definitions in controller or model,

Hope this helps!!!













Friday, 24 April 2015

Display only one row in CgridView in yii

Open the model from which the cgridview is generating and at the search method at the end add the bold font to the dataprovider 
i.e.,
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
// 'pagination'=>false,
'pagination'=>array(
'pageSize'=>'1',
), 
));
The above shows only one record in the  grid we can customize for more than one.
cheers!!

Generate Excel with search result from Cgridview in yii

First of all create a file with name "tlbExcelView.php" in 'protected/components/widgets' folder with the below bold content copied
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
<?php
Yii::import('zii.widgets.grid.CGridView');

/**
* @author Nikola Kostadinov
* @license MIT License
* @version 0.3
* @link http://yiiframework.com/extension/eexcelview/
*
* @fork 0.33ab
* @forkversion 1.1
* @author A. Bennouna
* @organization tellibus.com
* @license MIT License
* @link https://github.com/tellibus/tlbExcelView
*/

/* Usage :
  $this->widget('application.components.widgets.tlbExcelView', array(
    'id'                   => 'some-grid',
    'dataProvider'         => $model->search(),
    'grid_mode'            => $production, // Same usage as EExcelView v0.33
    //'template'           => "{summary}\n{items}\n{exportbuttons}\n{pager}",
    'title'                => 'Some title - ' . date('d-m-Y - H-i-s'),
    'creator'              => 'Your Name',
    'subject'              => mb_convert_encoding('Something important with a date in French: ' . utf8_encode(strftime('%e %B %Y')), 'ISO-8859-1', 'UTF-8'),
    'description'          => mb_convert_encoding('Etat de production généré à la demande par l\'administrateur (some text in French).', 'ISO-8859-1', 'UTF-8'),
    'lastModifiedBy'       => 'Some Name',
    'sheetTitle'           => 'Report on ' . date('m-d-Y H-i'),
    'keywords'             => '',
    'category'             => '',
    'landscapeDisplay'     => true, // Default: false
    'A4'                   => true, // Default: false - ie : Letter (PHPExcel default)
    'RTL'                  => false, // Default: false
    'pageFooterText'       => '&RThis is page no. &P of &N pages', // Default: '&RPage &P of &N'
    'automaticSum'         => true, // Default: false
    'decimalSeparator'     => ',', // Default: '.'
    'thousandsSeparator'   => '.', // Default: ','
    //'displayZeros'       => false,
    //'zeroPlaceholder'    => '-',
    'sumLabel'             => 'Column totals:', // Default: 'Totals'
    'borderColor'          => '00FF00', // Default: '000000'
    'bgColor'              => 'FFFF00', // Default: 'FFFFFF'
    'textColor'            => 'FF0000', // Default: '000000'
    'rowHeight'            => 45, // Default: 15
    'headerBorderColor'    => 'FF0000', // Default: '000000'
    'headerBgColor'        => 'CCCCCC', // Default: 'CCCCCC'
    'headerTextColor'      => '0000FF', // Default: '000000'
    'headerHeight'         => 10, // Default: 20
    'footerBorderColor'    => '0000FF', // Default: '000000'
    'footerBgColor'        => '00FFCC', // Default: 'FFFFCC'
    'footerTextColor'      => 'FF00FF', // Default: '0000FF'
    'footerHeight'         => 50, // Default: 20
    'columns'              => $grid // an array of your CGridColumns
)); */

class tlbExcelView extends CGridView
{
    //the PHPExcel object
    public $libPath = 'ext.phpexcel.Classes.PHPExcel'; //the path to the PHP excel lib
    public static $objPHPExcel = null;
    public static $activeSheet = null;

    //Document properties
    public $creator = 'Nikola Kostadinov';
    public $title = null;
    public $subject = 'Subject';
    public $description = '';
    public $category = '';
    public $lastModifiedBy = 'A. Bennouna';
    public $keywords = '';
    public $sheetTitle = '';
    public $legal = 'PHPExcel generator http://phpexcel.codeplex.com/ - EExcelView Yii extension http://yiiframework.com/extension/eexcelview/ - Adaptation by A. Bennouna http://tellibus.com';
    public $landscapeDisplay = false;
    public $A4 = false;
    public $RTL = false;
    public $pageFooterText = '&RPage &P of &N';

    //config
    public $autoWidth = true;
    public $exportType = 'Excel5';
    public $disablePaging = true;
    public $filename = null; //export FileName
    public $stream = true; //stream to browser
    public $grid_mode = 'grid'; //Whether to display grid ot export it to selected format. Possible values(grid, export)
    public $grid_mode_var = 'grid_mode'; //GET var for the grid mode

    //options
    public $automaticSum = false;
    public $sumLabel = 'Totals';
    public $decimalSeparator = '.';
    public $thousandsSeparator = ',';
    public $displayZeros = false;
    public $zeroPlaceholder = '-';
    public $border_style;
    public $borderColor = '000000';
    public $bgColor = 'FFFFFF';
    public $textColor = '000000';
    public $rowHeight = 15;
    public $headerBorderColor = '000000';
    public $headerBgColor = 'CCCCCC';
    public $headerTextColor = '000000';
    public $headerHeight = 20;
    public $footerBorderColor = '000000';
    public $footerBgColor = 'FFFFCC';
    public $footerTextColor = '0000FF';
    public $footerHeight = 20;
    public static $fill_solid;
    public static $papersize_A4;
    public static $orientation_landscape;
    public static $horizontal_center;
    public static $horizontal_right;
    public static $vertical_center;
    public static $style = array();
    public static $headerStyle = array();
    public static $footerStyle = array();
    public static $summableColumns = array();
    
    //buttons config
    public $exportButtonsCSS = 'summary';
    public $exportButtons = array('Excel2007');
    public $exportText = 'Export to: ';

    //callbacks
    public $onRenderHeaderCell = null;
    public $onRenderDataCell = null;
    public $onRenderFooterCell = null;
    
    //mime types used for streaming
    public $mimeTypes = array(
        'Excel5' => array(
            'Content-type'=>'application/vnd.ms-excel',
            'extension'=>'xls',
            'caption'=>'Excel(*.xls)',
        ),
        'Excel2007' => array(
            'Content-type'=>'application/vnd.ms-excel',
            'extension'=>'xlsx',
            'caption'=>'Excel(*.xlsx)',
        ),
        'PDF' =>array(
            'Content-type'=>'application/pdf',
            'extension'=>'pdf',
            'caption'=>'PDF(*.pdf)',
        ),
        'HTML' =>array(
            'Content-type'=>'text/html',
            'extension'=>'html',
            'caption'=>'HTML(*.html)',
        ),
        'CSV' =>array(
            'Content-type'=>'application/csv',
            'extension'=>'csv',
            'caption'=>'CSV(*.csv)',
        )
    );

    public function init()
    {
        if (isset($_GET[$this->grid_mode_var])) {
            $this->grid_mode = $_GET[$this->grid_mode_var];
        }
        if (isset($_GET['exportType'])) {
            $this->exportType = $_GET['exportType'];
        }
        $lib = Yii::getPathOfAlias($this->libPath).'.php';
        if (($this->grid_mode == 'export') && (!file_exists($lib))) {
            $this->grid_mode = 'grid';
            Yii::log("PHP Excel lib not found($lib). Export disabled !", CLogger::LEVEL_WARNING, 'EExcelview');
        }
            
        if ($this->grid_mode == 'export') {
            if (!isset($this->title)) {
                $this->title = Yii::app()->getController()->getPageTitle();
            }
            $this->initColumns();
            //parent::init();
            //Autoload fix
            spl_autoload_unregister(array('YiiBase','autoload'));             
            Yii::import($this->libPath, true);

            // Get here some PHPExcel constants in order to use them elsewhere
            self::$papersize_A4 = PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4;
            self::$orientation_landscape = PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE;
            self::$fill_solid = PHPExcel_Style_Fill::FILL_SOLID;
            if (!isset($this->border_style)) {
                $this->border_style = PHPExcel_Style_Border::BORDER_THIN;
            }
            self::$horizontal_center = PHPExcel_Style_Alignment::HORIZONTAL_CENTER;
            self::$horizontal_right = PHPExcel_Style_Alignment::HORIZONTAL_RIGHT;
            self::$vertical_center = PHPExcel_Style_Alignment::VERTICAL_CENTER;

            spl_autoload_register(array('YiiBase','autoload'));  

            // Creating a workbook
            self::$objPHPExcel = new PHPExcel();
            self::$activeSheet = self::$objPHPExcel->getActiveSheet();

            // Set some basic document properties
            if ($this->landscapeDisplay) {
                self::$activeSheet->getPageSetup()->setOrientation(self::$orientation_landscape);
            }

            if ($this->A4) {
                self::$activeSheet->getPageSetup()->setPaperSize(self::$papersize_A4);
            }

            if ($this->RTL) {
                self::$activeSheet->setRightToLeft(true);
            }

            self::$objPHPExcel->getProperties()
                ->setTitle($this->title)
                ->setCreator($this->creator)
                ->setSubject($this->subject)
                ->setDescription($this->description . ' // ' . $this->legal)
                ->setCategory($this->category)
                ->setLastModifiedBy($this->lastModifiedBy)
                ->setKeywords($this->keywords);

            // Initialize styles that will be used later
            self::$style = array(
                'borders' => array(
                    'allborders' => array(
                                        'style' => $this->border_style,
                                        'color' => array('rgb' => $this->borderColor),
                                    ),
                ),
                'fill' => array(
                    'type' => self::$fill_solid,
                    'color' => array('rgb' => $this->bgColor),
                ),
                'font' => array(
                    //'bold' => false,
                    'color' => array('rgb' => $this->textColor),
                )
            );
            self::$headerStyle = array(
                'borders' => array(
                    'allborders' => array(
                                        'style' => $this->border_style,
                                        'color' => array('rgb' => $this->headerBorderColor),
                                    ),
                ),
                'fill' => array(
                    'type' => self::$fill_solid,
                    'color' => array('rgb' => $this->headerBgColor),
                ),
                'font' => array(
                    'bold' => true,
                    'color' => array('rgb' => $this->headerTextColor),
                )
            );
            self::$footerStyle = array(
                'borders' => array(
                    'allborders' => array(
                                        'style' => $this->border_style,
                                        'color' => array('rgb' => $this->footerBorderColor),
                                    ),
                ),
                'fill' => array(
                    'type' => self::$fill_solid,
                    'color' => array('rgb' => $this->footerBgColor),
                ),
                'font' => array(
                    'bold' => true,
                    'color' => array('rgb' => $this->footerTextColor),
                )
            );
        } else {
            parent::init();
        }
    }

    public function renderHeader()
    {
        $a = 0;
        foreach ($this->columns as $column) {
            $a = $a + 1;
            if ($column instanceof CButtonColumn) {
                $head = $column->header;
            } else if (($column->header === null) && ($column->name !== null)) {
                if($column->grid->dataProvider instanceof CActiveDataProvider) {
                    $head = $column->grid->dataProvider->model->getAttributeLabel($column->name);
                } else {
                    $head = $column->name;
                }
            } else {
                $head =trim($column->header)!=='' ? $column->header : $column->grid->blankDisplay;
            }

            $cell = self::$activeSheet->setCellValue($this->columnName($a) . '1', $head, true);

            if (is_callable($this->onRenderHeaderCell)) {
                call_user_func_array($this->onRenderHeaderCell, array($cell, $head));
            }
        }

        // Format the header row
        $header = self::$activeSheet->getStyle($this->columnName(1) . '1:' . $this->columnName($a) . '1');
        $header->getAlignment()
            ->setHorizontal(self::$horizontal_center)
            ->setVertical(self::$vertical_center);
        $header->applyFromArray(self::$headerStyle);
        self::$activeSheet->getRowDimension(1)->setRowHeight($this->headerHeight);
    }

    public function renderBody()
    {
        if ($this->disablePaging) {
            //if needed disable paging to export all data
            $this->dataProvider->pagination = false;
        }
        $data = $this->dataProvider->getData();
        $n = count($data);

        if ($n > 0) {
            for ($row = 0; $row < $n; ++$row) {
                $this->renderRow($row);
            }
        }
        return $n;
    }

    public function renderRow($row)
    {
        $data = $this->dataProvider->getData();

        $a = 0;
        foreach ($this->columns as $n => $column) {
            if ($column instanceof CLinkColumn) {
                if ($column->labelExpression !== null) {
                    $value = $column->evaluateExpression($column->labelExpression, array('data' => $data[$row], 'row' => $row));
                } else {
                    $value = $column->label;
                }
            } else if ($column instanceof CButtonColumn) {
                $value = ""; //Dont know what to do with buttons
            } else if ($column->value !== null) {
                $value = $this->evaluateExpression($column->value, array('data' => $data[$row]));
            } else if ($column->name !== null) { 
                //$value = $data[$row][$column->name];
                $value = CHtml::value($data[$row], $column->name);
                $value = $value === null ? "" : $column->grid->getFormatter()->format($value, 'raw');
            }

            $a++;

            // Check if the cell value is a number, then format it accordingly
            // May be improved notably by exposing the formats as public
            // May be usable only for French-style number formatting ?
            if (preg_match("/^[0-9]*\\" . $this->thousandsSeparator . "[0-9]*\\" . $this->decimalSeparator . "[0-9]*$/", strip_tags($value))) {
                $content = str_replace($this->decimalSeparator, '.', str_replace($this->thousandsSeparator, '', strip_tags($value)));
                $format = '#\.##0.00';
            } else if (preg_match("/^[0-9]*\\" . $this->decimalSeparator . "[0-9]*$/", strip_tags($value))) {
                $content = str_replace($this->decimalSeparator, '.', strip_tags($value));
                $format = '0.00';
            } else if (!$this->displayZeros && ((strip_tags($value) === '0') || (strip_tags($value) === $this->zeroPlaceholder))) {
                $content = $this->zeroPlaceholder;
                self::$activeSheet->getStyle($this->columnName($a) . ($row + 2))->getAlignment()->setHorizontal(self::$horizontal_right);
                $format = '0.00';
            } else {
                $content = strip_tags($value);
                $format = null;
            }

            $cell = self::$activeSheet->setCellValue($this->columnName($a) . ($row + 2), $content, true);

            // Format each cell's number - if any
            if (!is_null($format)) {
                self::$summableColumns[$a] = $a;
                self::$activeSheet->getStyle($this->columnName($a) . ($row + 2))->getNumberFormat()->setFormatCode($format);
            }

            if(is_callable($this->onRenderDataCell)) {
                call_user_func_array($this->onRenderDataCell, array($cell, $data[$row], $value));
            }
        }

        // Format the row globally
        $renderedRow = self::$activeSheet->getStyle('A' . ($row + 2) . ':' . $this->columnName($a) . ($row + 2));
        $renderedRow->getAlignment()->setVertical(self::$vertical_center);
        $renderedRow->applyFromArray(self::$style);
        self::$activeSheet->getRowDimension($row + 2)->setRowHeight($this->rowHeight);
    }

    public function renderFooter($row)
    {
        $a = 0;
        foreach ($this->columns as $n => $column) {
            $a = $a + 1;
            if ($column->footer) {
                $footer = trim($column->footer) !== '' ? $column->footer : $column->grid->blankDisplay;

                $cell = self::$activeSheet->setCellValue($this->columnName($a) . ($row + 2), $footer, true);

                if(is_callable($this->onRenderFooterCell)) {
                    call_user_func_array($this->onRenderFooterCell, array($cell, $footer));
                }
            } else if ($this->automaticSum && in_array($a, self::$summableColumns)) {
                // We want to render automatic sums in the footer if no footer was already present in the grid
                $cell = self::$activeSheet->setCellValue($this->columnName($a) . ($row + 2), '=SUM(' . $this->columnName($a) . '2:' . $this->columnName($a) . ($row + 1) . ')', true);
                $sum = self::$activeSheet->getCell($this->columnName($a) . ($row + 2))->getCalculatedValue();
                if ($sum < 1000) {
                    $format = '0.00';                    
                } else if ($sum < 1000000) {
                    $format = '#\.##0.00';
                } else {
                    $format = '#\.###\.##0.00';
                }

                // We won't set the whole row's borders and number format, so proceed with each cell individually
                self::$activeSheet->getStyle($this->columnName($a) . ($row + 2))
                    ->applyFromArray(self::$footerStyle)
                    ->getNumberFormat()->setFormatCode($format);

                if(is_callable($this->onRenderFooterCell)) {
                    call_user_func_array($this->onRenderFooterCell, array($cell, $footer));
                }

                // Add a label before the first summable column (supposing it's not the first…)
                if (current(self::$summableColumns) == $a) {
                    $cell = self::$activeSheet->setCellValue($this->columnName($a - 1) . ($row + 2), $this->sumLabel, true);
                    self::$activeSheet->getStyle($this->columnName($a - 1) . ($row + 2))
                        ->applyFromArray(array('font' => array('bold' => true)))
                        ->getAlignment()->setHorizontal(self::$horizontal_right);
                    if(is_callable($this->onRenderFooterCell)) {
                        call_user_func_array($this->onRenderFooterCell, array($cell, $footer));
                    }
                }
            }
        }

        // Some global formatting for the footer in case of automatic sum
        if ($this->automaticSum) {
            self::$activeSheet->getStyle('A' . ($row + 2) . ':' . $this->columnName($a) . ($row + 2))->getAlignment()->setVertical(self::$vertical_center);
            self::$activeSheet->getRowDimension($row + 2)->setRowHeight($this->footerHeight);
        }
    }

    public function run()
    {
        if ($this->grid_mode == 'export') {
            $this->renderHeader();
            $row = $this->renderBody();
            $this->renderFooter($row);

            //set auto width
            if ($this->autoWidth) {
                foreach ($this->columns as $n => $column) {
                    $cell = self::$activeSheet->getColumnDimension($this->columnName($n + 1))->setAutoSize(true);
                }
            }

            // Set some additional properties
            self::$activeSheet
                ->setTitle($this->sheetTitle)
                ->getSheetView()->setZoomScale(50);
            self::$activeSheet->getHeaderFooter()
                ->setOddHeader('&C' . $this->sheetTitle)
                ->setOddFooter('&L&B' . self::$objPHPExcel->getProperties()->getTitle() . $this->pageFooterText);
            self::$activeSheet->getPageSetup()
                ->setPrintArea('A1:' . $this->columnName(count($this->columns)) . ($row + 2))
                ->setFitToWidth();

            //create writer for saving
            $objWriter = PHPExcel_IOFactory::createWriter(self::$objPHPExcel, $this->exportType);
            if (!$this->stream) {
                $objWriter->save($this->filename);
            } else {
                //output to browser
                if(!$this->filename) {
                    $this->filename = $this->title;
                }
                $this->cleanOutput();
                header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                header('Pragma: public');
                header('Content-type: '.$this->mimeTypes[$this->exportType]['Content-type']);
                header('Content-Disposition: attachment; filename="' . $this->filename . '.' . $this->mimeTypes[$this->exportType]['extension'] . '"');
                header('Cache-Control: max-age=0');
                $objWriter->save('php://output');
                Yii::app()->end();
            }
        } else {
            parent::run();
        }
    }

    /**
    * Returns the corresponding Excel column.(Abdul Rehman from yii forum)
    * 
    * @param int $index
    * @return string
    */
    public function columnName($index)
    {
        --$index;
        if (($index >= 0) && ($index < 26)) {
            return chr(ord('A') + $index);
        } else if ($index > 25) {
            return ($this->columnName($index / 26)) . ($this->columnName($index%26 + 1));
        } else {
            throw new Exception("Invalid Column # " . ($index + 1));
        }
    }
    
    public function renderExportButtons()
    {
        foreach ($this->exportButtons as $key => $button) {
            $item = is_array($button) ? CMap::mergeArray($this->mimeTypes[$key], $button) : $this->mimeTypes[$button];
            $type = is_array($button) ? $key : $button;
            $url = parse_url(Yii::app()->request->requestUri);
            //$content[] = CHtml::link($item['caption'], '?'.$url['query'].'exportType='.$type.'&'.$this->grid_mode_var.'=export');
            if (key_exists('query', $url)) {
                $content[] = CHtml::link($item['caption'], '?' . $url['query'] . '&exportType=' . $type . '&' . $this->grid_mode_var . '=export');          
            } else {
                $content[] = CHtml::link($item['caption'], '?exportType=' . $type . '&' . $this->grid_mode_var . '=export');
            }
        }
        if ($content) {
            echo CHtml::tag('div', array('class' => $this->exportButtonsCSS), $this->exportText.implode(', ', $content));
        }

    }
    
    /**
    * Performs cleaning on mutliple levels.
    * 
    * From le_top @ yiiframework.com
    * 
    */
    private static function cleanOutput() 
    {
        for ($level = ob_get_level(); $level > 0; --$level) {
            @ob_end_clean();
        }
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Now in our controller in admin action modify the code as follows, the bold font code is related to excel generation where as Italic font is related to search filters persistence even after the form submitted.

public function actionAdmin()
{
$model=new Demomodel('search');
$model->unsetAttributes();  // clear any default values
if(isset($_GET['Demomodel'])){
$model->attributes=$_GET['Demomodel'];
Yii::app()->user->setState('DemomodelSearchParams',$_GET['Demomodel']);
}else{
$searchParams = Yii::app()->user->getState('DemomodelSearchParams');
if(isset($searchParams)){
$model->attributes = $searchParams;   // This maintains the search result
}
}

if(isset($_GET['export'])){      // here is our excel code 
$production = 'export';
}else{
$production='grid';
}

$this->render('admin',array(
'model'=>$model,
'production' => $production,
));
}

Now in View i.e., in admin.php :

First of all register a client script, already there is some code exists for admin.php view in register script add the below bold font lines to the script.

Yii::app()->clientScript->registerScript('search', "
$('#exportToExcel').click(function(){
window.location = '". $this->createUrl('admin'). "' +
$(this).parents('form').serialize() + '&export=true';
return false;
});
$('.search-button').click(function(){
$('.search-form').toggle();
return false;
});
$('.search-form form').submit(function(){
$('#Demomodel-grid').yiiGridView('update', {
data: $(this).serialize()
});
return false;
});
");


after that add the export excel button to the form using the below statement

<?php echo CHtml::button(Yii::t('app', 'Export to Excel (xls)'), array('id' => 'exportToExcel')); ?>

Now the CgridView to be changed as follows in our case lets consider our demo model has 3 fields id,name,office and gender. now the grid to be defined as follows , the new lines are showed in bold font. Here we are taking gender as drop down to recollect previous post, However by defining drop down in only view will not work, have to define in model, that is explained in previous post.


<?php
$this->widget('application.components.widgets.tlbExcelView',  
                    // changed from zii.widgets.grid.CGridView'
    array(
      'id'                   => 'demomodel',
    'dataProvider'         => $model->search(),
    'filter'   => $model,
    'grid_mode'            => $production, // Same usage as EExcelView v0.33
    //'template'           => "{summary}\n{items}\n{exportbuttons}\n{pager}",
    'title'                => 'ExcelSheetName_' . date('d_m_Y_His'),  
// sheet name to be defined here we have taken date,month,year with time to make sure no overriding
    'creator'              => 'Organization name ',
/*    'subject'              => mb_convert_encoding('Something important with a date in French: ' . utf8_encode(strftime('%e %B %Y')), 'ISO-8859-1', 'UTF-8'),
    'description'          => mb_convert_encoding('Etat de production généré à la demande par l\'administrateur (some text in French).', 'ISO-8859-1', 'UTF-8'), */
//    'lastModifiedBy'       => 'Some Name',
    'sheetTitle'           => 'Report on ' . date('d-M-Y H-i'),
    'keywords'             => '',
    'category'             => '',
    'landscapeDisplay'     => true, // Default: false
    'A4'                   => true, // Default: false - ie : Letter (PHPExcel default)
    'RTL'                  => false, // Default: false - since v1.1
    'pageFooterText'       => '&RThis is page no. &P of &N pages', // Default: '&RPage &P of &N'
    'automaticSum'         => false, // Default: false
    'decimalSeparator'     => '.', // Default: '.'
    'thousandsSeparator'   => ',', // Default: ','
    //'displayZeros'       => false,
    //'zeroPlaceholder'    => '-',
  //  'sumLabel'             => 'Column totals:', // Default: 'Totals'
    'borderColor'          => '00FF00', // Default: '000000'
    'bgColor'              => 'FFFFFF', // Default: 'FFFFFF'
    'textColor'            => '000000', // Default: '000000'
    'rowHeight'            => 45, // Default: 15
    'headerBorderColor'    => 'FF0000', // Default: '000000'
    'headerBgColor'        => 'CCCCCC', // Default: 'CCCCCC'
    'headerTextColor'      => '0000FF', // Default: '000000'
    'headerHeight'         => 20, // Default: 20
    'footerBorderColor'    => '0000FF', // Default: '000000'
    'footerBgColor'        => '00FFCC', // Default: 'FFFFCC'
    'footerTextColor'      => 'FF00FF', // Default: '0000FF'
    'footerHeight'         => 50, // Default: 20
    'columns'              => array(
id,
                name,
                office,
                 array(
                         'name'=>'gender',
                         'header'=>'Gender', 
                         'value'=>'Demomodel::getGender($data->gender)',
                        'filter'=>CHtml::listData(Demomodel::getGenders(),'id','title'),
                 ),
array(
'class'=>'CButtonColumn',
),
),
)); ?>


Finally, don't miss to give the permissions to all files in case of linux machines. Now the excel generations completed. Play as you want :)






DropDown in filters instead of text boxes in Cgridview in YII

First of all,
We need to define methods in Model to generate options for Dropdown

Lets take a example GENDER, The gender can be male or female. This is simple example for drop down

Don't go for drop down if there are more than 10 options , which makes grid sluggish

Now, Lets assume we have field name "gender" in our model, so the methods defined in model are as follows

public static function getGenders( )
{
return array(
array('id'=>'','title'=>'Select'),
array('id'=>'M', 'title'=>'Male'),
array('id'=>'F', 'title'=>'Female'),
);
}
public static function getGender($onoff)
{
if($onoff == 'M')
return 'Male';
elseif($onoff == 'F')
return 'Female';
else
return $onoff;
/* elseif(($onoff == 'T')or($onoff == null))
return 'NIL'; */
}

There is no need to change or add any code in controller,

Now coming to view the admin.php consisting of CgridView at the columns definition

<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'demomodel-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
id,
name,
office,
array(
'name'=>'gender',
'header'=>'Gender', // This is displayed in grid only for heading purpose
'value'=>'Demomodel::getGender($data->gender)',
// Here getgender called for value to grid
'filter'=>CHtml::listData(Demomodel::getGenders(),'id','title'),
// Where as for Filters getGenders( ) is used.
),
array(
'class'=>'CButtonColumn',
),
),
)); ?>

Now the drop down displayed in place of textbox for filtering

Friday, 17 April 2015

Setting a CRON Job in UBUNTU




Cron job written so automatic backup doing by the server.

Setting A CRON Job in UBUNTU :


Method 1:

1. Goto Super User by giving the command #su root (here is the super user is root not the same in every system)

2.  man crontab -- gives the detials about the crontab, if needed check the document once before proceeding, if the command not existing install Gnome schedule task tool.

Install "Gnome schedule tasks tool", to install this use the command as
 # sudo apt-get install gnome-schedule

3. start the crontab in terminal using the command

    #crontab -e (should be super user to execute this command)  
    for help use the command ( #man 5 crontab ).
  +--------------------------------------------------------------------+
  |  -e --> editor                                                 |
  |  -l  --> current job display on standard output     |
  |  -r  --> current crontab to be removed                |
  +--------------------------------------------------------------------+

4. Before editing or assigning a task check the command which is going to added in crontab executing or not from the current location.

5. Here in this case, the shell file "bakup.sh" is in /usr/bin/server/bakup folder. so the line added at the end is

   0 0 * * * user_name sh /usr/bin/server/bakup/bakup.sh

   The above command executes on every day at 12 A.M, ie., the db backup taken at every day midnight.

  Another example,

  0 3 * * 0 root /sbin/shutdown -r +5

 The above command restart the server at 3 A.M on every sunday.

  +---------------------------------------------------------------------------------------------------------------------------------------------+
  | Format is minute(0-59) hour(0-23,0=midnight) day(1-31) month(1-12) weekday(0-6,0 or 7=sunday)  |
  | 0 0 * * *        --->  midnight on everyday  |
  | 0 0 * * 1-5     --->  midnight every weekday  |
  | 0 0 1,15 * *   --->  midnight on 1st and 15th of month  |
  | 0 0 1 * 5       --->  midnight on 1st of month and every friday  |
  +---------------------------------------------------------------------------------------------------------------------------------------------+


Method 2:

1. Login as root user and execute the following command.
    # vim /etc/crontab.

2. At the end of the file add the line of command which is to be executed

     0 0 * * * user_name sh /usr/bin/server/bakup/bakup.sh  (Here in our case, the shell file "bakup.sh" is in /usr/bin/server/bakup folder. so the line added at the end)
 

Manual for cron job settings:


Linux Crontab Format

MIN HOUR DOM MON DOW CMD
Table: Crontab Fields and Allowed Ranges (Linux Crontab Syntax)
Field Description Allowed Value
MIN Minute field 0 to 59
HOUR Hour field 0 to 23
DOM Day of Month 1-31
MON Month field 1-12
DOW Day Of Week 0-6
CMD Command Any command to be executed.

1. Scheduling a Job For a Specific Time

The basic usage of cron is to execute a job in a specific time as shown below. This will execute the Full backup shell script (full-backup) on 10th June 08:30 AM.

Please note that the time field uses 24 hours format. So, for 8 AM use 8, and for 8 PM use 20.

30 08 10 06 * /home/ramesh/full-backup
30 – 30th Minute
08 – 08 AM
10 – 10th Day
06 – 6th Month (June)
* – Every day of the week

2. Schedule a Job For More Than One Instance (e.g. Twice a Day)

The following script take a incremental backup twice a day every day.

This example executes the specified incremental backup shell script (incremental-backup) at 11:00 and 16:00 on every day. The comma separated value in a field specifies that the command needs to be executed in all the mentioned time.

00 11,16 * * * /home/ramesh/bin/incremental-backup
00 – 0th Minute (Top of the hour)
11,16 – 11 AM and 4 PM
* – Every day
* – Every month
* – Every day of the week

3. Schedule a Job for Specific Range of Time (e.g. Only on Weekdays)

If you wanted a job to be scheduled for every hour with in a specific range of time then use the following.

Cron Job everyday during working hours

This example checks the status of the database everyday (including weekends) during the working hours 9 a.m – 6 p.m

00 09-18 * * * /home/ramesh/bin/check-db-status
00 – 0th Minute (Top of the hour)
09-18 – 9 am, 10 am,11 am, 12 am, 1 pm, 2 pm, 3 pm, 4 pm, 5 pm, 6 pm
* – Every day
* – Every month
* – Every day of the week
Cron Job every weekday during working hours

This example checks the status of the database every weekday (i.e excluding Sat and Sun) during the working hours 9 a.m – 6 p.m.

00 09-18 * * 1-5 /home/ramesh/bin/check-db-status
00 – 0th Minute (Top of the hour)
09-18 – 9 am, 10 am,11 am, 12 am, 1 pm, 2 pm, 3 pm, 4 pm, 5 pm, 6 pm
* – Every day
* – Every month
1-5 -Mon, Tue, Wed, Thu and Fri (Every Weekday)

4. How to View Crontab Entries?

View Current Logged-In User’s Crontab entries

To view your crontab entries type crontab -l from your unix account as shown below.

ramesh@dev-db$ crontab -l
@yearly /home/ramesh/annual-maintenance
*/10 * * * * /home/ramesh/check-disk-space

[Note: This displays crontab of the current logged in user]
View Root Crontab entries

Login as root user (su – root) and do crontab -l as shown below.

root@dev-db# crontab -l
no crontab for root
Crontab HowTo: View Other Linux User’s Crontabs entries

To view crontab entries of other Linux users, login to root and use -u {username} -l as shown below.

root@dev-db# crontab -u sathiya -l
@monthly /home/sathiya/monthly-backup
00 09-18 * * * /home/sathiya/check-db-status

5. How to Edit Crontab Entries?

Edit Current Logged-In User’s Crontab entries

To edit a crontab entries, use crontab -e as shown below. By default this will edit the current logged-in users crontab.

ramesh@dev-db$ crontab -e
@yearly /home/ramesh/centos/bin/annual-maintenance
*/10 * * * * /home/ramesh/debian/bin/check-disk-space
~
"/tmp/crontab.XXXXyjWkHw" 2L, 83C

[Note: This will open the crontab file in Vim editor for editing.
Please note cron created a temporary /tmp/crontab.XX... ]
When you save the above temporary file with :wq, it will save the crontab and display the following message indicating the crontab is successfully modified.

~
"crontab.XXXXyjWkHw" 2L, 83C written
crontab: installing new crontab
Edit Root Crontab entries

Login as root user (su – root) and do crontab -e as shown below.

root@dev-db# crontab -e
Edit Other Linux User’s Crontab File entries

To edit crontab entries of other Linux users, login to root and use -u {username} -e as shown below.

root@dev-db# crontab -u sathiya -e
@monthly /home/sathiya/fedora/bin/monthly-backup
00 09-18 * * * /home/sathiya/ubuntu/bin/check-db-status
~
~
~
"/tmp/crontab.XXXXyjWkHw" 2L, 83C

6. Schedule a Job for Every Minute Using Cron.

Ideally you may not have a requirement to schedule a job every minute. But understanding this example will will help you understand the other examples mentioned below in this article.

* * * * * CMD
The * means all the possible unit — i.e every minute of every hour through out the year. More than using this * directly, you will find it very useful in the following cases.

When you specify */5 in minute field means every 5 minutes.
When you specify 0-10/2 in minute field mean every 2 minutes in the first 10 minute.
Thus the above convention can be used for all the other 4 fields.

7. Schedule a Background Cron Job For Every 10 Minutes.

Use the following, if you want to check the disk space every 10 minutes.

*/10 * * * * /home/ramesh/check-disk-space
It executes the specified command check-disk-space every 10 minutes through out the year. But you may have a requirement of executing the command only during office hours or vice versa. The above examples shows how to do those things.

Instead of specifying values in the 5 fields, we can specify it using a single keyword as mentioned below.

There are special cases in which instead of the above 5 fields you can use @ followed by a keyword — such as reboot, midnight, yearly, hourly.

Table: Cron special keywords and its meaning
Keyword Equivalent
@yearly 0 0 1 1 *
@daily 0 0 * * *
@hourly 0 * * * *
@reboot Run at startup.

8. Schedule a Job For First Minute of Every Year using @yearly

If you want a job to be executed on the first minute of every year, then you can use the @yearly cron keyword as shown below.

This will execute the system annual maintenance using annual-maintenance shell script at 00:00 on Jan 1st for every year.

@yearly /home/ramesh/red-hat/bin/annual-maintenance

9. Schedule a Cron Job Beginning of Every Month using @monthly

It is as similar as the @yearly as above. But executes the command monthly once using @monthly cron keyword.

This will execute the shell script tape-backup at 00:00 on 1st of every month.

@monthly /home/ramesh/suse/bin/tape-backup

10. Schedule a Background Job Every Day using @daily

Using the @daily cron keyword, this will do a daily log file cleanup using cleanup-logs shell scriptat 00:00 on every day.

@daily /home/ramesh/arch-linux/bin/cleanup-logs "day started"

11. How to Execute a Linux Command After Every Reboot using @reboot?

Using the @reboot cron keyword, this will execute the specified command once after the machine got booted every time.

@reboot CMD

12. How to Disable/Redirect the Crontab Mail Output using MAIL keyword?

By default crontab sends the job output to the user who scheduled the job. If you want to redirect the output to a specific user, add or update the MAIL variable in the crontab as shown below.

ramesh@dev-db$ crontab -l
MAIL="ramesh"

@yearly /home/ramesh/annual-maintenance
*/10 * * * * /home/ramesh/check-disk-space

[Note: Crontab of the current logged in user with MAIL variable]

If you wanted the mail not to be sent to anywhere, i.e to stop the crontab output to be emailed, add or update the MAIL variable in the crontab as shown below.

MAIL=""

13. How to Execute a Linux Cron Jobs Every Second Using Crontab.

You cannot schedule a every-second cronjob. Because in cron the minimum unit you can specify is minute. In a typical scenario, there is no reason for most of us to run any job every second in the system.

14. Specify PATH Variable in the Crontab

All the above examples we specified absolute path of the Linux command or the shell-script that needs to be executed.

For example, instead of specifying /home/ramesh/tape-backup, if you want to just specify tape-backup, then add the path /home/ramesh to the PATH variable in the crontab as shown below.

ramesh@dev-db$ crontab -l

PATH=/bin:/sbin:/usr/bin:/usr/sbin:/home/ramesh

@yearly annual-maintenance
*/10 * * * * check-disk-space

[Note: Crontab of the current logged in user with PATH variable]

15. Installing Crontab From a Cron File

Instead of directly editing the crontab file, you can also add all the entries to a cron-file first. Once you have all thoese entries in the file, you can upload or install them to the cron as shown below.

ramesh@dev-db$ crontab -l
no crontab for ramesh

$ cat cron-file.txt
@yearly /home/ramesh/annual-maintenance
*/10 * * * * /home/ramesh/check-disk-space

ramesh@dev-db$ crontab cron-file.txt

ramesh@dev-db$ crontab -l
@yearly /home/ramesh/annual-maintenance

*/10 * * * * /home/ramesh/check-disk-space
Note: This will install the cron-file.txt to your crontab, which will also remove your old cron entries. So, please be careful while uploading cron entries from a cron-file.txt.