<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Arvind Gupta</title>
	<atom:link href="http://www.arvindgupta.co.in/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.arvindgupta.co.in</link>
	<description></description>
	<lastBuildDate>Thu, 26 Jan 2012 04:27:44 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
<xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" />
		<item>
		<title>Analgyph (3D) Images</title>
		<link>http://www.arvindgupta.co.in/experiments/analgyph-3d-images/</link>
		<comments>http://www.arvindgupta.co.in/experiments/analgyph-3d-images/#comments</comments>
		<pubDate>Mon, 08 Aug 2011 10:07:52 +0000</pubDate>
		<dc:creator>Arvind</dc:creator>
				<category><![CDATA[Experiments]]></category>

		<guid isPermaLink="false">http://www.arvindgupta.co.in/?p=74</guid>
		<description><![CDATA[Some analgyph images I shot using a regular camera. Two shots had to be taken from two different positions and post-processed to create these. They look quite satisfactory to me!]]></description>
			<content:encoded><![CDATA[<p>Some <a href="http://en.wikipedia.org/wiki/Anaglyph_image">analgyph images</a> I shot using a regular camera. Two shots had to be taken from two different positions and post-processed to create these. They look quite satisfactory to me!</p>
<div class="ngg-imagebrowser" id="ngg-imagebrowser-7-74">

	<h3>Flower Vase (Anaglyphic 3D)</h3>

	<div class="pic">
<a href="http://www.arvindgupta.co.in/wp-content/gallery/anaglyphic-3d/3d2.jpg" title="Please use red-cyan glasses to see this image." class="shutterset_anaglyphic-3d">
	<img alt="Flower Vase (Anaglyphic 3D)" src="http://www.arvindgupta.co.in/wp-content/gallery/anaglyphic-3d/3d2.jpg"/>
</a>
</div>
	<div class="ngg-imagebrowser-nav"> 
		<div class="back">
			<a class="ngg-browser-prev" id="ngg-prev-27" href="http://www.arvindgupta.co.in/experiments/analgyph-3d-images/?pid=27">&#9668; Back</a>
		</div>
		<div class="next">
			<a class="ngg-browser-next" id="ngg-next-24" href="http://www.arvindgupta.co.in/experiments/analgyph-3d-images/?pid=24">Next &#9658;</a>
		</div>
		<div class="counter">Picture 1 of 4</div>
		<div class="ngg-imagebrowser-desc"><p>Please use red-cyan glasses to see this image.</p></div>
	</div>	

</div>	

]]></content:encoded>
			<wfw:commentRss>http://www.arvindgupta.co.in/experiments/analgyph-3d-images/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Evil MySQL Subquery and High Server Load</title>
		<link>http://www.arvindgupta.co.in/mysql/evil-mysql-subqueries-and-high-server-load/</link>
		<comments>http://www.arvindgupta.co.in/mysql/evil-mysql-subqueries-and-high-server-load/#comments</comments>
		<pubDate>Wed, 20 Apr 2011 11:43:12 +0000</pubDate>
		<dc:creator>Arvind</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[optimization]]></category>
		<category><![CDATA[subquery]]></category>

		<guid isPermaLink="false">http://www.arvindgupta.co.in/?p=56</guid>
		<description><![CDATA[For a long time I’d been seeing high server load on the server MyWapBlog.com is hosted. I thought the increasing traffic was the cause. MySQL, I knew was the casing the load, but I thought it was all natural for a dynamic site with NO caching. One day, just when I was seriously thinking about [...]]]></description>
			<content:encoded><![CDATA[<p>For a long time I’d been seeing high server load on the  server MyWapBlog.com is hosted. I thought the increasing traffic was the cause.  MySQL, I knew was the casing the load, but I thought it was all natural for a  dynamic site with NO caching.</p>
<p>One day, just when I was seriously thinking about  implementing some kind of caching, I found about <code><a href="http://mtop.sourceforge.net">mtop</a></code>  &#8211; small tool like <code>top</code> to display running MySQL queries in real-time, running it I found that every second there were  many queries (same query but made by different requests) that got stuck in the  “PREPARING” state and sometimes took as long as 2 secs. to complete. The evil  query was:</p>
<pre class="brush: sql; title: ; notranslate">
SELECT c.post_id FROM category_post_relationship c
  WHERE  (c.cat_id IN
  (SELECT c2.id AS c2__id FROM categories c2
  WHERE (c2.user_id =  ?)))
</pre>
<p>Thinking what it does? Let me make it easier &#8211; it fetches  “post ids” of all the posts of a user that are categorized.</p>
<p>1. Running the query</p>
<p>184 rows, Query took 0.0812 sec</p>
<p>2. Profiling:</p>
<pre>   starting &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;    0.000132
   checking permissions &nbsp;&nbsp; 0.000011
   checking permissions &nbsp;&nbsp; 0.000011
   Opening tables          0.000037
   System lock &nbsp;&nbsp;&nbsp;&nbsp;        0.000015
   Table lock &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;      &nbsp; 0.000022
   init &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;             0.000065
   optimizing &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;     &nbsp; 0.000025
   statistics &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  &nbsp;&nbsp;&nbsp; 0.000027
   preparing &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;     &nbsp; 0.000027
   executing &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;     &nbsp; 0.000011
   Sending data &nbsp;&nbsp;&nbsp;        0.000047
   optimizing &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;      0.000023
   statistics &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;   0.000086
   preparing &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;      0.075275
   end &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;               0.000015
   query end &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;       0.000010
   freeing items &nbsp;&nbsp;&nbsp;       0.000033
   logging slow query &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0.000009
   cleaning up &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;       0.000011</pre>
<p>3. EXPLAIN:</p>
<pre style="font-size: 10px;"><strong>id 	    select_type         table       type 	       possible_keys 	    key         key_len    ref 	    row     Extra</strong>
1 	    PRIMARY 	        c 	    index 	       NULL 	            PRIMARY 	8 	   NULL     53898   Using where; Using index
2 	    DEPENDENT SUBQUERY 	c2 	    unique_subquery    PRIMARY,user_id 	    PRIMARY 	4 	   func     1 	    Using where</pre>
<p>If you’d ask some novice to do what the query does many of  them would use two separate queries and believe me (I’ve done the testing as  well) that’ll be much faster!</p>
<p>Googling “subquery optimization” got me this:</p>
<blockquote>
<p>MySQL evaluates queries “from outside to inside.” That  is, it first obtains the value of the outer expression outer_expr, and then  runs the subquery and captures the rows that it produces. </p>
<p>From <a href="http://dev.mysql.com/doc/refman/5.1/en/in-subquery-optimization.html">http://dev.mysql.com/doc/refman/5.1/en/in-subquery-optimization.html</a></p>
</blockquote>
<p>The page also tells us some tips on how to optimize  subqueries, going by the suggestions we get the following query:</p>
<pre class="brush: sql; title: ; notranslate">
SELECT c.post_id FROM category_post_relationship c
  WHERE  EXISTS
  (SELECT 1 FROM categories c2
  WHERE c2.user_id = 7639 AND c.cat_id =  c2.id)
</pre>
<p>Still, running it takes similar query times and as such  doesn’t help.</p>
<p>Again from the same page:</p>
<blockquote>
<p>After the conversion, MySQL can use the pushed-down  equality to limit the number of rows that it must examine when evaluating the  subquery.</p>
</blockquote>
<p>Though I didn’t read the whole page thoroughly (I’m lazy and  since I got the job done by some other technique) still I’m sure that  this “optimized” query only “optimizes” the subquery while our biggest problem  is that the outer table (with about 50000 rows) is getting evaluated.</p>
<p>I felt, this was one query you’d rather not “optimize” and  be happy with two separate queries.</p>
<p>But, this is not to say it can’t be optimized, it can be  very easily – by NOT using subqueries at all. I used JOINS:</p>
<pre class="brush: sql; title: ; notranslate">
SELECT cc.post_id FROM categories c
  RIGHT JOIN category_post_relationship cc
  ON  c.id = cc.cat_id&lt;br&gt;
  WHERE  c.user_id = ?
</pre>
<p>Now the query takes 0.0008 sec compared to 0.0812, that’s a  hundred fold improvement!</p>
<p>Some tips:</p>
<ol>
<li>If you’re using subqueries and are having some problems  with it being slow read the article I mentioned.
  </li>
<li>If possible, use <code>WHERE</code> condition on the outer query.
    </li>
<li>Don’t use subqueries when the outer query table contains  lots of rows. (I may be wrong but this is what I’ve found out) </li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://www.arvindgupta.co.in/mysql/evil-mysql-subqueries-and-high-server-load/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP Data Validation Class</title>
		<link>http://www.arvindgupta.co.in/php/php-data-validation-class/</link>
		<comments>http://www.arvindgupta.co.in/php/php-data-validation-class/#comments</comments>
		<pubDate>Sat, 09 Apr 2011 11:48:51 +0000</pubDate>
		<dc:creator>Arvind</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.arvindgupta.co.in/?p=27</guid>
		<description><![CDATA[Created this data validation class a couple of days back for validating some forms. Thought it might be useful for others. This one’s very basic and light-weight but still fully working with many pre-defined rules. Before listing the class, let me first show how it’s used: Very straightforward! Validating a form is equally straightforward. The [...]]]></description>
			<content:encoded><![CDATA[<p>Created this data validation class a couple of days back for validating some forms. Thought it might be useful for others. This one’s very basic and light-weight but still fully working with many pre-defined rules.</p>
<p>Before listing the class, let me first show how it’s used:</p>
<pre class="brush: php; title: ; notranslate">
require 'Validator.class.php';

$validator = new Validator();

// Add rules
$validator-&gt;addRule('name', array('minlength' =&gt; 5, 'maxlength' =&gt; 20));
$validator-&gt;addRule('age', array('min' =&gt; 13, 'max' =&gt; 35));
$validator-&gt;addRule('url', array('url'));
$validator-&gt;addRule('about', array('require'));

// Data to be validated, would normally come from a form
$data = array(
        'name' =&gt; 'Arvind Gupta',
        'age' =&gt; '80',
        'url' =&gt; 'http:www.arvindgupta',
);

// Set data to be validated
$validator-&gt;setData($data);

// Check
if ($validator-&gt;isValid())
{
    echo '&lt;h1&gt;Data is valid!&lt;/h1&gt;';
}
else
{
    echo '&lt;h1&gt;Data is not valid!&lt;/h1&gt;';
    echo '&lt;ol&gt;';

    // Get and print errors in a nice manner
    foreach ($validator-&gt;getErrors() as $field =&gt; $messages)
    {
        if (count($messages) == 1)
        {
            echo &quot;&lt;li&gt;&lt;strong&gt;$field&lt;/strong&gt;: $messages[0]&lt;/li&gt;&quot;;
        }
        else
        {
            // If a field has more than one error
            echo &quot;&lt;li&gt;&lt;strong&gt;$field&lt;/strong&gt;:&lt;/li&gt;&quot;;
            echo '&lt;ol&gt;';
            foreach ($messages as $message)
            {
                echo &quot;&lt;li&gt;$message&lt;/li&gt;&quot;;
            }
            echo '&lt;/ol&gt;';
        }
    }
    echo '&lt;/ol&gt;';
}
</pre>
<p>Very straightforward!</p>
<p>Validating a form is equally straightforward. The best way would be to have the form elements named like arrays, for example:</p>
<pre class="brush: xml; light: true; title: ; notranslate">
&lt;form ...&gt;
	&lt;input type=&quot;text&quot; name=&quot;form1[text1]&quot; value=&quot;&quot; /&gt;
	&lt;input type=&quot;text&quot; name=&quot;form1[text2]&quot; value=&quot;&quot; /&gt;
&lt;/form&gt;
</pre>
<p>And, use something the following line to provide the form data to the validator at one go:</p>
<pre class="brush: php; light: true; title: ; notranslate">
$validator-&gt;setData($_REQUEST['form1']);
</pre>
<p>That&#8217;s it! Here is the class code:</p>
<pre class="brush: php; title: ; notranslate">
/**
 * Validator
 *
 * Data validation class
 *
 * @author      Arvind Gupta &lt;contact [ AT ] arvindgupta [ DOT ] co [ DOT ] in&gt;
 * @copyright   Arvind Gupta (c) 2011
 * @link        http://www.arvindgupta.co.in
 * @license     You're free to do whatever with this as long as this notice
 *              remains intact.
 */
class Validator
{

    protected $_rules = array();
    protected $_data = array();
    protected $_messages = array();
    protected $_errors = array();

    public function __construct()
    {
        $this-&gt;setDefaultMessages();
    }

    /**
     * Add a rule
     *
     * @param string $field	Field name (index of data to be validated)
     * @param array  $rules	Array of rule(s)
     */
    public function addRule($field, array $rules)
    {
        $this-&gt;_rules[$field] = $rules;
    }

    /**
     * Set data to be validated
     *
     * @param array $data   Data to be validated
     */
    public function setData(array $data)
    {
        $this-&gt;_data = $data;
    }

    /**
     * Set error message for rule
     *
     * @param string $rule	Rule name
     * @param string $message	New message
     */
    public function setMessage($rule, $message)
    {
        $this-&gt;_messages[$rule] = $message;
    }

    /**
     * Validates current data with current rules
     *
     * @return boolean
     */
    public function isValid()
    {
        $valid = true;
        foreach ($this-&gt;_rules as $field =&gt; $rules)
        {
            $value = isset($this-&gt;_data[$field]) ? $this-&gt;_data[$field] : '';

            foreach ($rules as $rule =&gt; $parameter)
            {
                // If rule does not require parameter
                if (is_int($rule))
                {
                    $rule = $parameter;
                    $parameter = null;
                }

                if (!$this-&gt;check($value, $rule, $parameter))
                {
                    $valid = false;

                    if (stripos($this-&gt;_messages[$rule], '%s') !== false)
                    {
                        $this-&gt;_errors[$field][] = sprintf($this-&gt;_messages[$rule], $parameter);
                    }
                    else
                    {
                        $this-&gt;_errors[$field][] = $this-&gt;_messages[$rule];
                    }
                }
            }
        }

        return $valid;
    }

    /**
     * Get error messages if validation fails
     *
     * @return array	Error messages
     */
    public function getErrors()
    {
        return $this-&gt;_errors;
    }

    protected function check($value, $rule, $parameter)
    {
        switch ($rule)
        {
            case 'require' :
                return!(trim($value) == '');

            case 'maxlength' :
                return (strlen($value) &lt;= $parameter);

            case 'minlength' :
                return (strlen($value) &gt;= $parameter);

            case 'numeric' :
                return is_numeric($value);

            case 'int' :
                return is_int($value);

            case 'min' :
                return $value &gt; $parameter ? true : false;

            case 'max' :
                return $value &lt; $parameter ? true : false;

            case 'url':
                // Regex taken from symfony
                return preg_match('~^
			      (https?)://                               # protocol
			      (
				([a-z0-9-]+\.)+[a-z]{2,6}               # a domain name
				  |                                     #  or
				\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}      # a IP address
			      )
			      (:[0-9]+)?                                # a port (optional)
			      (/?|/\S+)                                 # a /, nothing or a / with something
			    $~ix', $value);

            case 'email':
                return preg_match('/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i', $value);

            case 'regex':
                return preg_match($parameter, $value);

            case 'pass':
                return true;

            default :
                return false;
        }
    }

    protected function setDefaultMessages()
    {
        $this-&gt;_messages = array(
                'require' =&gt; 'Field is required.',
                'maxlength' =&gt; 'Too long (%s characters max).',
                'minlength' =&gt; 'Too short (%s characters min).',
                'numeric' =&gt; 'Value must be numeric.',
                'int' =&gt; 'Value must be an integer.',
                'max' =&gt; 'Value must be at most %s',
                'min' =&gt; 'Value must be at least %s',
                'url' =&gt; 'Value must be a valid URL.',
                'email' =&gt; 'Value must be a valid email.',
                'regex' =&gt; 'Invalid value.',
        );
    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.arvindgupta.co.in/php/php-data-validation-class/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Goodbye website…</title>
		<link>http://www.arvindgupta.co.in/personal/goodbye-website/</link>
		<comments>http://www.arvindgupta.co.in/personal/goodbye-website/#comments</comments>
		<pubDate>Sat, 09 Apr 2011 06:27:24 +0000</pubDate>
		<dc:creator>Arvind</dc:creator>
				<category><![CDATA[Personal]]></category>

		<guid isPermaLink="false">http://www.arvindgupta.co.in/wordpress/?p=17</guid>
		<description><![CDATA[So, here and now I bid farewell to my previous website that existed here for over 2 years. I was planning on running a blog instead for quite a while but lacked enough motivation. Now that I have finally created a blog here, I plan on publishing posts on everything from programming to publishing photographs [...]]]></description>
			<content:encoded><![CDATA[<p>So, here and now I bid farewell to my previous website that  existed here for over 2 years. I was planning on running a blog instead for quite a while but lacked enough motivation.</p>
<p>Now that I have finally created a blog here, I plan on publishing posts on everything  from programming to publishing photographs I shoot on a regular basis (not all  that frequently though). Read my <a href="http://www.arvindgupta.co.in/about-me/">About Me</a> page for more information about me.</p>
<p style="text-align: center;"><img class="size-full wp-image-18" title="Screenshot of Old Website" src="http://www.arvindgupta.co.in/wp-content/uploads/2011/04/old-website.jpg" alt="Screenshot of old website" width="400" height="340" /><br />Screenshot of the previous website</p>
]]></content:encoded>
			<wfw:commentRss>http://www.arvindgupta.co.in/personal/goodbye-website/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Page Caching using disk: enhanced
Database Caching 5/36 queries in 0.068 seconds using apc
Object Caching 744/812 objects using apc

Served from: www.arvindgupta.co.in @ 2012-05-20 19:47:26 -->
