Monday, 20 November 2017

Email template optimization tools

  Here is the list of email templates optimization tools. Remember to exclude media query if you have for responsive design. They will not work properly if inline. Some time might face a problem that your responsive design is not working on some of the email clients. The reason might be of character limit. The stylesheet is then checked against a 8,192 character limit. If your stylesheet, after processing, exceeds the limit, the whole stylesheet gets removed from your email.    

Push notification IOS

Push notification IOS  
<?php

// authentication
$host = "localhost";
$user = "user";
$pass = "pass";
$dbname = "DB";

// create connection with database
$con = mysql_connect($host, $user, $pass);

// check whether database connection is successful
if (!$con) {
// if connection not successful then stop the script and show the error
    die('Could not connect to database: ' . mysql_error());
} else {
// if database connection successful then select the database
    mysql_select_db($dbname, $con);
}

// get the id, token from database
$query = "SELECT `notifications`.`id` as pid, `notifications`.`by_userid`, `notifications`.`userid`, `notifications`.`messege`, `notifications`.`is_read`,  `users`.`id`, `users`.`name`, `users`.`email`, `users`.`dob`, `users`.`gender`,  `users`.`profile_pic`, `users`.`device_id` FROM `table`.`notifications` AS `notifications`  INNER JOIN `table2`.`users` AS `users` ON (`notifications`.`userid` = `users`.`id`) WHERE `notifications`.`is_read` = '0' ";
$result = mysql_query($query);
$data = mysql_fetch_array($result);
$count = count($data);

//Setup notification message
$body = array();
$body['aps'] = array('alert' => $data['messege']);
$body['aps']['notifurl'] = 'yourwebsite.com/push_new.php';
$body['aps']['badge'] = $count;
$body['aps']['messege'] = $data['messege'];
$body['aps']['id'] = $data['pid'];
$id = $data['pid'];

//Setup stream (connect to Apple Push Server)
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'passphrase', '123456');
stream_context_set_option($ctx, 'ssl', 'local_cert', 'certificate.pem'); // add your .pem file
$fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
stream_set_blocking($fp, 0);
// This allows fread() to return right away when there are no errors. But it can also miss errors during
//  last  seconds of sending, as there is a delay before error is returned. Workaround is to pause briefly
// AFTER sending last notification, and then do one more fread() to see if anything else is there.

if (!$fp) {
//ERROR
    echo "Failed to connect (stream_socket_client): $err $errstrn";
} else {

// Keep push alive (waiting for delivery) for 90 days
    $apple_expiry = time() + (90 * 24 * 60 * 60);

// Loop thru tokens from database
    while ($row = mysql_fetch_array($result)) {
        $apple_identifier = $row["id"];
        $deviceToken = $row['device_id'];
        $payload = json_encode($body);

// Enhanced Notification
        $msg = pack("C", 1) . pack("N", $apple_identifier) . pack("N", $apple_expiry) . pack("n", 32) . pack('H*', str_replace(' ', '', $deviceToken)) . pack("n", strlen($payload)) . $payload;

// SEND PUSH
        fwrite($fp, $msg);

// We can check if an error has been returned while we are sending, but we also need to
// check once more after we are done sending in case there was a delay with error response.
        checkAppleErrorResponse($fp);
    }

// Workaround to check if there were any errors during the last seconds of sending.
// Pause for half a second.
// Note I tested this with up to a 5 minute pause, and the error message was still available to be retrieved
    usleep(500000);

    checkAppleErrorResponse($fp);

    echo 'Completed';
    $query = "UPDATE `notifications` SET `is_read` = 1 WHERE id = $id ";
    $results = mysql_query($query);
    mysql_close($con);
    fclose($fp);
}

// FUNCTION to check if there is an error response from Apple
// Returns TRUE if there was and FALSE if there was not
function checkAppleErrorResponse($fp) {

//byte1=always 8, byte2=StatusCode, bytes3,4,5,6=identifier(rowID).
// Should return nothing if OK.
//NOTE: Make sure you set stream_set_blocking($fp, 0) or else fread will pause your script and wait
// forever when there is no response to be sent.

    $apple_error_response = fread($fp, 6);

    if ($apple_error_response) {

// unpack the error response (first byte 'command" should always be 8)
        $error_response = unpack('Ccommand/Cstatus_code/Nidentifier', $apple_error_response);

        if ($error_response['status_code'] == '0') {
            $error_response['status_code'] = '0-No errors encountered';
        } else if ($error_response['status_code'] == '1') {
            $error_response['status_code'] = '1-Processing error';
        } else if ($error_response['status_code'] == '2') {
            $error_response['status_code'] = '2-Missing device token';
        } else if ($error_response['status_code'] == '3') {
            $error_response['status_code'] = '3-Missing topic';
        } else if ($error_response['status_code'] == '4') {
            $error_response['status_code'] = '4-Missing payload';
        } else if ($error_response['status_code'] == '5') {
            $error_response['status_code'] = '5-Invalid token size';
        } else if ($error_response['status_code'] == '6') {
            $error_response['status_code'] = '6-Invalid topic size';
        } else if ($error_response['status_code'] == '7') {
            $error_response['status_code'] = '7-Invalid payload size';
        } else if ($error_response['status_code'] == '8') {
            $error_response['status_code'] = '8-Invalid token';
        } else if ($error_response['status_code'] == '255') {
            $error_response['status_code'] = '255-None (unknown)';
        } else {
            $error_response['status_code'] = $error_response['status_code'] . '-Not listed';
        }

        echo '<br><b>+ + + + + + ERROR</b> Response Command:<b>' . $error_response['command'] . '</b>&nbsp;&nbsp;&nbsp;Identifier:<b>' . $error_response['identifier'] . '</b>&nbsp;&nbsp;&nbsp;Status:<b>' . $error_response['status_code'] . '</b><br>';

        echo 'Identifier is the rowID (index) in the database that caused the problem, and Apple will disconnect you from server. To continue sending Push Notifications, just start at the next rowID after this Identifier.<br>';

        return true;
    }

    return false;
}
?>
 

Push notification Android Php

Hey, Today we learn how to send push notification for android in php. First create a class with following code  
<?php

class Pusher{
    const GOOGLE_GCM_URL = 'https://android.googleapis.com/gcm/send';
    private $apiKey;
    private $proxy;
    private $output;
    public function __construct($apiKey, $proxy = null)
    {
        $this->apiKey = 'your_key';
        $this->proxy  = $proxy;
    }
    /**
     * @param string|array $regIds
     * @param string $data
     * @throws Exception
     */
    public function notify($regIds, $data)
    {
//        pr($data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, self::GOOGLE_GCM_URL);
        if (!is_null($this->proxy)) {
            curl_setopt($ch, CURLOPT_PROXY, $this->proxy);
        }
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $this->getHeaders());
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $this->getPostFields($regIds, $data));
        $result = curl_exec($ch);
        if ($result === false) {
            throw new Exception(curl_error($ch));
        }
        curl_close($ch);
//        pr($result); die;
        $this->output = $result;
        return $result;
    }
    /**
     * @return array
     */
    public function getOutputAsArray()
    {
        return json_decode($this->output, true);
    }
    /**
     * @return object
     */
    public function getOutputAsObject()
    {
        return json_decode($this->output);
    }

    private function getHeaders(){
        return [
            'Authorization: key=' . $this->apiKey,
            'Content-Type: application/json'
        ];
    }

    private function getPostFields($regIds, $data){
        $fields = [
            'registration_ids' => is_string($regIds) ? [$regIds] : $regIds,
            'data'             => is_string($data) ? ['message' => $data] : $data,
        ];
        return json_encode($fields, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE);
    }
}
now call your notify function by creating a object of pusher class.  
 $notification = array("title" => $title,
            "message" => $message,
            "data" => $data,
        );

 $pusher = new Pusher($apiKey);
            $pusher->notify($reg_ids, $notification); // reg_ids are the device ids on which you want to send push
If you are using cakephp or any other php framework then add pusher class in you plugin folder(appPluginPusherPusher.php) and load it where you want to use.

codility brackets opening and closing solution

codility you are given a string s consisting of n brackets opening problem solution.  
function isBalanced($str){
    $count = 0;
    $ocount = 0;
    $ccount = 0;
    $length = strlen($str);
    for($i = 0; $i < $length; $i++){
        if($str[$i] == '(')
            $ocount += 1;
        else if($str[$i] == ')')
            $ccount += 1;
       if($ccount == $ocount){
          $count = $ocount;
       }else{
            $count = $ccount;
       }
    }
    return $count;
}
echo isBalanced("))");
 

How to download multiple files at once - in single command

Suppose you have approx 1000 image files for download, then here is a command to download all them.
  1. Create a text file named it urls.txt
  2. enter all urls each url in a new line
  3. type WGET -i urls.txt in your terminal
WGET -i urls.txt
 

CakePHP in a subdirectory using nginx

CakePHP in a subdirectory using nginx

I was facing many issues in setup cakephp3 in subfolder on nginx server. I was doing changes in new server config while we have to do that in existing server config(well that work for me :) ) So I just add following in default config file. Which can be found /etc/nginx/sites-available  
location /youproj{
alias /usr/share/nginx/html/public_html/youproj/webroot;
if (-f $request_filename) {
break;
}

# prevent recursion
if ($request_uri ~ /webroot/index.php) {
break;
}

rewrite ^/youproj$ /youproj/ permanent;
rewrite ^/youproj/webroot/(.*) /youproj/webroot/index.php?url=$1 last;
rewrite ^/youproj/(.*)$ /youproj/webroot/$1 last;
}
  And enable base_url in app.php in config folder of cakephp
'App' => [
'namespace' => 'App',
'encoding' => env('APP_ENCODING', 'UTF-8'),
'defaultLocale' => env('APP_DEFAULT_LOCALE', 'en_US'),
'base' => false,
'dir' => 'src',
'webroot' => 'webroot',
'wwwRoot' => WWW_ROOT,
'baseUrl' => env('SCRIPT_NAME'),
'base' => '/mamonde',
'fullBaseUrl' => false,
'imageBaseUrl' => 'img/',
'cssBaseUrl' => 'css/',
'jsBaseUrl' => 'js/',
'paths' => [
'plugins' => [ROOT . DS . 'plugins' . DS],
'templates' => [APP . 'Template' . DS],
'locales' => [APP . 'Locale' . DS],
],
],
     

Friday, 1 April 2016

export database table php

export database table php

Sometime there is need to export database table by php code. There is a very simple approach to do this.   ]export database table by php
export database table by php
/*******EDIT LINES 3-8*******/
$DB_Server = "localhost"; //MySQL Server    
$DB_Username = ""; //MySQL Username     
$DB_Password = "";             //MySQL Password     
$DB_DBName = "";         //MySQL Database Name  
$DB_TBLName = "tablename"; //MySQL Table Name   
$filename = "Student_export-".time();         //File Name
/*******YOU DO NOT NEED TO EDIT ANYTHING BELOW THIS LINE*******/    
//create MySQL connection   
$sql = "SELECT * FROM  ".$DB_TBLName ;
$Connect = @mysql_connect($DB_Server, $DB_Username, $DB_Password)
 or die("Couldn't connect to MySQL:<br>" . mysql_error() . "<br>" . mysql_errno());
//select database   
$Db = @mysql_select_db($DB_DBName, $Connect) 
or die("Couldn't select database:<br>" . mysql_error(). "<br>" . mysql_errno());   
//execute query
$result = @mysql_query($sql,$Connect) 
or die("Couldn't execute query:<br>" . mysql_error(). "<br>" . mysql_errno());    
$file_ending = "xls";
//header info for browser
header("Content-Type: application/xls");    
header("Content-Disposition: attachment; filename=$filename.xls");  
header("Pragma: no-cache");
header("Expires: 0");
/*******Start of Formatting for Excel*******/   
//define separator (defines columns in excel & tabs in word)
$sep = "\t"; //tabbed character
//start of printing column names as names of MySQL fields
for ($i = 0; $i < mysql_num_fields($result); $i++) {
echo mysql_field_name($result,$i) . "\t";
}
print("\n");    
//end of printing column names  
//start while loop to get data
    while($row = mysql_fetch_row($result))
    {
        $schema_insert = "";
        for($j=0; $j<mysql_num_fields($result);$j++)
        {
            if(!isset($row[$j]))
                $schema_insert .= "NULL".$sep;
            elseif ($row[$j] != "")
                $schema_insert .= "$row[$j]".$sep;
            else
                $schema_insert .= "".$sep;
        }
        $schema_insert = str_replace($sep."$", "", $schema_insert);
        $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
        $schema_insert .= "\t";
        print(trim($schema_insert));
        print "\n";
    }  
    die;

Thursday, 9 October 2014

Simple Responsive Slider using jquery




Here is a Simple Responsive Slider using jquery which works on every breakpoints. A very simple js/jquery which helps you to modify it according to your requirements.
Download  infinite_Image_Carousel-master

Custom linkedin button for share and auth









  1. <script src="http://platform.linkedin.com/in.js">
  2. api_key:
  3. //onLoad: onLinkedInLoad
  4. scope: r_basicprofile r_emailaddress r_fullprofile
  5. authorize:true
  6. </script>
  7. <script>
  8. function onLinkedInAuth() {
  9. IN.API.Profile("me")
  10. .fields("firstName", "lastName", "industry", "location:(name)", "picture-url", "headline", "summary", "num-connections", "public-profile-url", "distance", "positions", "email-address", "educations", "date-of-birth")
  11. .result(displayProfiles);
  12. IN.UI.Share().params({
  13. url: "http://www.example.com"
  14. }).place()
  15. }

  16. function displayProfiles(profiles) {
  17. console.log(profiles);
  18. member = profiles.values[0];
  19. }

  20. jQuery(document).ready(function(){
  21. jQuery("#linkdinlog").click(function(){
  22. IN.UI.Authorize().place();
  23. IN.Event.on(IN, "auth", onLinkedInAuth);
  24. });
  25. });
  26. </script><a href="javascript:void(0)" id="linkdinlog">link</a>

remove svn files folder using php

some time we forget to export a project on svn and upload that on main server. Result , our main server now have svn file and folders folders. if we want to delete them we have to delete them one by one (if your svn version is old) or we have to upload a new copy of project by exporting project using SVN. It may take a quit long time. So here is the alternate. By using this code you can delete all svn files and folders at once.








  1. $path = $_SERVER['DOCUMENT_ROOT'].'/work/remove-svn-php/'; // path of your directory
  2. header( 'Content-type: text/plain' ); // plain text for easy display

  3. // preconditon: $dir ends with a forward slash (/) and is a valid directory
  4. // postcondition: $dir and all it's sub-directories are recursively
  5. // searched through for .svn directories. If a .svn directory is found,
  6. // it is deleted to remove any security holes.
  7. function removeSVN( $dir ) {
  8. //echo "Searching: $dirnt";

  9. $flag = false; // haven't found svn directory
  10. $svn = $dir . '.svn';

  11. if( is_dir( $svn ) ) {
  12. if( !chmod( $svn, 0777 ) )
  13. echo "File permissions could not be changed (this may or may not be a problem--check the statement below).nt"; // if the permissions were already 777, this is not a problem

  14. delTree( $svn ); // remove the .svn directory with a helper function

  15. if( is_dir( $svn ) ) // deleting failed
  16. echo "Failed to delete $svn due to file permissions.";
  17. else
  18. echo "Successfully deleted $svn from the file system.";

  19. $flag = true; // found directory
  20. }

  21. if( !$flag ) // no .svn directory
  22. echo 'No .svn directory found.';
  23. echo "nn";

  24. $handle = opendir( $dir );
  25. while( false !== ( $file = readdir( $handle ) ) ) {
  26. if( $file == '.' || $file == '..' ) // don't get lost by recursively going through the current or top directory
  27. continue;

  28. if( is_dir( $dir . $file ) )
  29. removeSVN( $dir . $file . '/' ); // apply the SVN removal for sub directories
  30. }
  31. }

  32. // precondition: $dir is a valid directory
  33. // postcondition: $dir and all it's contents are removed
  34. // simple function found at http://www.php.net/manual/en/function.rmdir.php#93836
  35. function delTree( $dir ) {
  36. $files = glob( $dir . '*', GLOB_MARK ); // find all files in the directory

  37. foreach( $files as $file ) {
  38. if( substr( $file, -1 ) == '/')
  39. delTree( $file ); // recursively apply this to sub directories
  40. else
  41. unlink( $file );
  42. }

  43. if ( is_dir( $dir ) ){
  44. //echo $dir;
  45. // die;
  46. rmdir( $dir ); // remove the directory itself (rmdir only removes a directory once it is empty)

  47. }
  48. }

  49. // remove all .svn directories in the
  50. // current directory and sub directories
  51. // (recursively applied)
  52. removeSVN($path);


Tuesday, 31 December 2013

update product quantity on check out page magento


you can do it by editing item.phtml (template/checkout/onepage/review/item.phtml) and these lines after line no #47

    <td class="a-center"><?php echo $_item->getQty() ?></td> 
        <td class="a-center">
            <input name="cart[<?php echo $_item->getId() ?>][qty]" value="<?php echo $this->getQty() ?>" size="4" name="update_cart_action" id="cup_<?php echo $_item->getId() ?>"  class="input-text qty" maxlength="12" />
        </td>
       <td> <button type="submit" name="update_cart_action" value="update_qty" title="<?php echo $this->__('shopping-cart-table'); ?>" id="up_<?php echo $_item->getId() ?>" class="button btn-update"><span><span><?php echo $this->__('Update'); ?></span></span></button><td>

and put Jquery code at the end

    <script type="text/javascript">
    jQuery(document).ready(function(){
        jQuery(".btn-update").click(function(){

            var id = "#c"+this.id;
            var quan = jQuery(id).val();
            var lastChar = id.substr(id.length - 1);

            jQuery.ajax({
                url: "<?php echo Mage::getBaseUrl(); ?>checkout/cart/updatePosts/",
                data: "cart["+lastChar+"][qty]="+quan,
                async: false,
                    success: function(html){

                        location.reload();

                    }
            })
        })
    })
    </script>now override cartcontroller.php and place all the functions of the original cartcontroller.php and rename function updatePostAction by function updatePostsAction.
and change the redirect path to $this->_redirect('checkout/onepage');

Put magento on maintenance mode and it open only on your ip








Today I am going to explain you how to put magento on maintenance mode. That maintenance mode will show to all other user user beside you. So can can work on a live environment if there is any issue.
Some time we all face a problem that something is not working on live environment while it is working on staging. So we have to test it on live environment but it is more difficult to put echo/ die on live site.
you can you do your work by using these steps so only you are able to open site while other see site is under maintenance mode.
Step 1 : put a file on your root with the name “maintenance.flag”
Step 2 : open you index file and find the code
if (file_exists($maintenanceFile) ) {
include_once dirname(__FILE__) . ‘/errors/503.php’;
exit;
}
Now update the code with that code
$ip = $_SERVER['REMOTE_ADDR']; // you can check your ip by http://who.is/
if (file_exists($maintenanceFile) && $ip != “your ip address” ) {
include_once dirname(__FILE__) . ‘/errors/503.php’;
exit;
}

unzip folder and files using php code

<!--?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
// using $_SERVER['DOCUMENT_ROOT'] if you don't know the where you are
    $zip->extractTo('/my/destination/dir/');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>

set permission for magento (magento-cleaning)

If you are facing issue of permissions or internal server error then try to set permission to magento folder that might help you.
set 777 for media , var and app/etc folder
and for rest of file and folders create a file with name “magento-cleaning.php” and paste the blow code in that file and put this on root folder and hit this in url.
example: http://www.yourdomain.com/magento-cleaning.php

<?php
## Function to set file permissions to 0644 and folder permissions to 0755
function AllDirChmod( $dir = “./”, $dirModes = 0755, $fileModes = 0644 ){
   $d = new RecursiveDirectoryIterator( $dir );
   foreach( new RecursiveIteratorIterator( $d, 1 ) as $path ){
      if( $path->isDir() ) chmod( $path, $dirModes );
      else if( is_file( $path ) ) chmod( $path, $fileModes );
  }
}
## Function to clean out the contents of specified directory
function cleandir($dir) {
    if ($handle = opendir($dir)) {
        while (false !== ($file = readdir($handle))) {
            if ($file != ‘.’ && $file != ‘..’ && is_file($dir.’/’.$file)) {
                if (unlink($dir.’/’.$file)) { }
                else { echo $dir . ‘/’ . $file . ‘ (file) NOT deleted!<br />’; }
            }
            else if ($file != ‘.’ && $file != ‘..’ && is_dir($dir.’/’.$file)) {
                cleandir($dir.’/’.$file);
                if (rmdir($dir.’/’.$file)) { }
                else { echo $dir . ‘/’ . $file . ‘ (directory) NOT deleted!<br />’; }
            }
        }
        closedir($handle);
    }
}
function isDirEmpty($dir){
     return (($files = @scandir($dir)) && count($files) <= 2);
}
echo “———————– CLEANUP START ————————-<br/>”;
$start = (float) array_sum(explode(‘ ‘,microtime()));
echo “
*************** SETTING PERMISSIONS ***************
“;
echo “Setting all folder permissions to 755<br/>”;
echo “Setting all file permissions to 644<br/>”;
AllDirChmod( “.” );
echo “Setting pear permissions to 550<br/>”;
chmod(“pear”, 550);
echo “<br/>****************** CLEARING CACHE ******************<br/>”;
if (file_exists(“var/cache”)) {
    echo “Clearing var/cache<br/>”;
    cleandir(“var/cache”);
}
if (file_exists(“var/session”)) {
    echo “Clearing var/session<br/>”;
    cleandir(“var/session”);
}
if (file_exists(“var/minifycache”)) {
    echo “Clearing var/minifycache<br/>”;
    cleandir(“var/minifycache”);
}
if (file_exists(“downloader/pearlib/cache”)) {
    echo “Clearing downloader/pearlib/cache
“;
    cleandir(“downloader/pearlib/cache”);
}
if (file_exists(“downloader/pearlib/download”)) {
    echo “Clearing downloader/pearlib/download
“;
    cleandir(“downloader/pearlib/download”);
}
if (file_exists(“downloader/pearlib/pear.ini”)) {
    echo “Removing downloader/pearlib/pear.ini
“;
    unlink (“downloader/pearlib/pear.ini”);
}
echo “<br/>************** CHECKING FOR EXTENSIONS ***********<br/>”;
If (!isDirEmpty(“app/code/local/”)) {
    echo “-= WARNING =- Overrides or extensions exist in the app/code/local folder<br/>”;
}
If (!isDirEmpty(“app/code/community/”)) {
    echo “-= WARNING =- Overrides or extensions exist in the app/code/community folder<br/>”;
}
$end = (float) array_sum(explode(‘ ‘,microtime()));
echo “
——————- CLEANUP COMPLETED in:”. sprintf(“%.4f”, ($end-$start)).” seconds ——————
“;
?>

Wednesday, 24 April 2013

copy a file into another folder in asp .net

string targetFolder = Server.MapPath(“~/PDF”);
System.IO.FileInfo fi = new System.IO.FileInfo(Server.MapPath(“~/Bookmark.pdf”));
fi.CopyTo(System.IO.Path.Combine(targetFolder, fi.Name), true);

get product thumb images on view.phtml

<!–?<?php $_images = Mage::getModel(‘catalog/product’)->load($_product->getId())->getMediaGalleryImages(); ?>
<?php if($_images){?>
<?php $i=0; foreach($_images as $_image){ $i++; ?>
<a href=”#” onclick=”ig_lightbox_show(-1)”>

<img src=”<?php echo $this->helper(‘catalog/image’)->init($_product, ‘thumbnail’, $_image->getFile())->resize(108,90); ?>” alt=”<?php echo $this->htmlEscape($_image->getLabel());?>” title=”<?php $this->htmlEscape($_image->getLabel());?>” />
</a><?php } ?> <?php } ?>

how to check canvas is empty or not

<canvas id="canvas11″ height=”200px” width=”200px”>
<asp:Button runat=”server” ID=”btn1″ Text=”Save”  OnClientClick=”checkcanvas();” />
<script type=”text/javascript”>
function checkcanvas() {
var i = isCanvasTransparent();
//i =true    if canvas empty
//i =false       if canvas has image
}
function isCanvasTransparent() {
var canvas1 = document.getElementById(‘canvas11′);
// true if all pixels Alpha equals to zero
var ctx = canvas1.getContext(“2d”);
var result;
var imageData = ctx.getImageData(0, 0, canvas1.offsetWidth, canvas1.offsetHeight);
for (var i = 0; i < imageData.data.length; i += 4)
if (imageData.data[i + 3] !== 0) return false;
return true;
}
</script>

countdown timer in php,

$dateFormat = “d F Y — g:i a”;
$targetDate = $futureDate;//Change the 25 to however many minutes you want to countdown change date in strtotime
$actualDate = $date1;
$secondsDiff = $targetDate – $actualDate;
$remainingDay     = floor($secondsDiff/60/60/24);
$remainingHour    = floor(($secondsDiff-($remainingDay*60*60*24))/60/60);
$remainingMinutes = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))/60);
$remainingSeconds = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))-($remainingMinutes*60));
$actualDateDisplay = date($dateFormat,$actualDate);
$targetDateDisplay = date($dateFormat,$targetDate);
<script type=”text/javascript”>
var days = <?php echo $remainingDay; ?>
var hours = <?php echo $remainingHour; ?>
var minutes = <?php echo $remainingMinutes; ?>
var seconds = <?php echo $remainingSeconds; ?>
function setCountDown(statusfun)
{//alert(seconds);
var SD;
if(days >= 0 && minutes >= 0){
var dataReturn =  jQuery.ajax({
type: “GET”,
url: “<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB).’index.php/countdowncont/’; ?>”,
async: true,
success: function(data){
var data = data.split(“/”);
day =  data[0];
hours =  data[1];
minutes =  data[2];
seconds =  data[3];
}
});
seconds–;
if (seconds < 0){
minutes–;
seconds = 59
}
if (minutes < 0){
hours–;
minutes = 59
}
if (hours < 0){
days–;
hours = 23
}
document.getElementById(“remain”).style.display = “block”;
document.getElementById(“remain”).innerHTML = ” Your Product Reverse For “+minutes+” minutes, “+seconds+” seconds”;
SD=window.setTimeout( “setCountDown()”, 1000 );
}else{
document.getElementById(“remain”).innerHTML = “”;
seconds = “00″; window.clearTimeout(SD);
jQuery.ajax({
type: “GET”,
url: “<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB).’index.php/countdown/’; ?>”,
async: false,
success: function(html){
}
});
document.getElementById(“remain”).innerHTML = “”;
window.location = document.URL; // Add your redirect url
}
}
</script>
<?php
if($date1 < $futureDate &&  ($qtyCart > 0)){ ?>
<script type=”text/javascript”>
setCountDown();
</script>
<?php }else{ ?>
<style>
#remain{display:none;}
</style>
<?php }}?>
<div id=”remain”></div>

some mysql queries

1. Add column age and desg in emp_prof table.
Mysql> use profile;
Mysql>alter table emp_prof add column age int;
Mysql> alter table emp_prof add column desg char(10);

2. Update all records of emp_prof.(desg= actn,officer)
Mysql> use profile;
Mysql>update emp_prof set age=24,desg=’officer’ where emp_id=101;
Mysql>update emp_prof set age=21,desg=’actn’ where emp_id=102;
(follow above queries for other records)

3. Display all records from emp_prof where age is 24 and designation is actn.
Mysql> use profile;
Mysql>select * from emp_prof where age=24 and desg=’actn’;

4. Display all records from emp_prof where age is 24 or designation is actn.
Mysql> use profile;
Mysql>select * from emp_prof where age=24 or desg=’actn’;

5.Display emp_name and age where age is not below 25
Mysql> use profile;
Mysql>select emp_name from emp_prof where not age<25;

6.Display emp_name and age where age between 21 and 25
Mysql> use profile;
Mysql> select emp_name from emp_prof where age between 21 and 25;

7.Display name and age where age is not between 23 and 26.
Mysql> use profile;
Mysql>select emp_name from emp_prof where not age between 23 and 26;

8.Display emp_name and country where reperesenting country (‘india’,’australia’)
Mysql> use profile;
Mysql>select emp_name,country from emp_prof where country in (‘india’,’australia’);

9. Display emp_name from emp_prof where emp_name starting with alphabet s.
Mysql> use profile;
Mysql>select emp_name from emp_prof where emp_name like ‘s%’;

10. Display all records from table cust_prof where fname is ending with alphabet s.
Mysql> use profile;
Mysql>select fname from cust_prof where fname like ‘%s’;

11. Display all records from table cust_prof where fname contains alphabet z.
Mysql> use profile;
Mysql>select * from cust_prof where fname like ‘%z%’;

12. Display all records from table cust_prof where lname contains alphabet ‘is’.
Mysql> use profile;
Mysql>select * from cust_prof where lname like ‘%is%’;

13. Display all records from table cust_prof where uppercase ‘A’ is present in fname.
Mysql> use profile;
Mysql>select * from cust_prof where fname like binary ‘%A%’;

  1. Display fname and lname from cust_prof where lowercase ‘t’ is present in fname.
Mysql> use profile;
Mysql>select fname,lname from cust_prof where fname like binary ‘%t%’;

15. Display fname and lname from cust_prof table where 2nd character of fname is ‘a’.(like ‘_a%’)
Mysql> use profile;
Mysql>select fname,lname from cust_prof where fname like  ‘_a%’;

16. Display emp_names from emp_prof  where 2nd last character of the name is ‘e’. (like ‘%e_’)
Mysql> use profile;
Mysql>select emp_name from emp_prof where emp_name like ‘%e_’;


17. Display emp_name from emp_prof where emp_name has exact 5 charecters. ( like ‘_ _ _ _ _ ‘)
Mysql> use profile;
Mysql>select emp_name from emp_prof where emp_name  like ‘_ _ _ _ _’;

18. Display emp_name from emp_prof where name contains ‘s’ first and then ‘i’ somewhere thereafter.
Mysql> use profile;
Mysql>select emp_name from emp_prof where emp_name like ‘s%i%’;

19. Display emp_name from emp_prof where emp_name second character of name is ‘a’ and contains ‘p’ somewhere after thereafter.(like ‘_a%p%’)
Mysql> use profile;
Mysql>select emp_name from emp_prof where emp_name like ‘_a%p%’;

20. Display emp_names from emp_prof where emp_name second character of emp_name is ‘a’ and last character of name is ‘s’. (like ‘_a%s’)
Mysql> use profile;
Mysql>select emp_name from emp_prof where emp_name like ‘_a%s’;

recursive function for getting parent and child

function categoryChild($id) {
$s = “SELECT ID FROM PLD_CATEGORY WHERE PARENT_ID = $id”;
$r = mysql_query($s);
$children = array();
if(mysql_num_rows($r) > 0) {
# It has children, let’s get them.
while($row = mysql_fetch_array($r)) {
# Add the child to the list of children, and get its subchildren
$children[$row['ID']] = categoryChild($row['ID']);
}
}
return $children;
}