Blog
Array to Hash in Ruby
To be able to converting hash into array in Ruby is easy but how do we convert an array into a hash? This tutorial did the ruby array to hash trick.
class Array
def to_hash(other)
Hash[ *(0...self.size()).inject([]) { |arr, ix| arr.push(self[ix], other[ix]) } ]
end
end
%W{ a b c }.to_hash( %W{ 1 2 3 } )
#=> {"a"=>"1", "b"=>"2", "c"=>"3"}
If you are looking to wonder what hash map is, check out this Ruby Hash.
- Log in to post comments
Mysql "If exists update else insert" performance dilemma

Everyone who uses databases is in the habit of using "If exists update else insert" in the software program. Irrespective of the software program (Oracle, Mysql, Sql Server) and irrespective of the language (Php, ASP, Java). Ever wondered what is the efficient way of doing it.
Typically, we do it this way:
IF EXISTS (SELECT * FROM Table1 WHERE Column1='SomeValue')
UPDATE Table1 SET (...) WHERE Column1='SomeValue'
ELSE
INSERT INTO Table1 VALUES (...)
This is inherently slow. Why? It scans the whole database table by first doing a select and then updates or inserts. By default 2 step process. Imagine if we can reduce the number of steps:
$result = mysql_query("update test set col='test' where col_id='1';");
if (mysql_affected_rows()==0) {
$result = mysql_query("insert into test (col_id, col) values ('1','test');");
}
This is faster since we have reduced the number of always 2 step to sometimes 1 step.
Anyother way that we can improve this further?
Note: Learn to do: mysql string replace
- Log in to post comments
Creating a PDF file with PHP: Tutorial

In PHP, we have a nice open source library for PDF file generation, FPDF. This library has an extention FPDI that allows for manipulating PDF files. FPDI extracts the content of the pdf, allows you to change it and then output the changed pdf.
Example Usage: FPDF. Creating First PDF file.
Download and unzip FPDF package and include it in your php script. The following code gives an example on how to create your first pdf file named myfile.pdf:
<?php require('fpdf.php'); $pdf=new FPDF(); $pdf->AddPage(); $pdf->SetFont('Arial','B',16); $pdf->Cell(40,10,'Hello World!');$pdf->Output('myFile.pdf', 'F');?>
The above code creates a downloadable pdf file (myFile.pdf) from the php code with "Hello World" in it. Here, we are first creating a PDF object, then adding a page. In the new page, we then set the font style to Arial with font size 16. Next, we create a cell with 40px wide and 10px height that contains the text "Hello World".
For more examples on pdf manipulation with your php code, checkout the link.
- Log in to post comments
Top 5 Javascript slider
Are you in search of the 'X' factor for your website which could scale it up from its boring look and feel?
You must consider introducing a bit of Javascript element and see the difference. A Javascript slider would be a good first beginning. Images always give a cutting edge to any website and if it is in a slide-show format with beautiful transitional effects what else could you be asking for?
Use Javascript sliders to add life to your website. Let us profile the Top 5 Javascript sliders for you so that you can make up that decision:
JCarousel - One of the most popular jQuery plugin which is used to display a list of images in a vertical/horizontal fashion thereby adding value to your website. You will have to include the jQuery library, the jCarousel source file and jCarousel library stylesheet inside the tag of your HTML document.

Smooth Gallery - To improvise and make your website stand out use the Smooth Gallery JS slider on your website. This gallery slider supports cross fading slide transitions and gives your website a tidy look.

Noobslide - One of the vastly improved slide-show script the Noobslide provides you with eye-catching slide transition effects. This excellent slide-show gallery is sure to enhance the look and feel of your website.

Space Gallery - This one is certainly one of our favorite overlap slider effect javascript style addition which can bring your website to life.

Mopslider - MopSlider is a jQuery plugin which provides the ability to have multiple content types on a single slider gallery. You can have a combination of flash, images and HTML on the slider which works amazingly well across browsers.

Learn to submit form using Javascript.
- Log in to post comments
Speed up your website using GZIP
Browser v/s Server – Optimizing Site Using GZIP Compression
In the online world if ever a browser and server interacted in a chat environment, this is what would definitely come up:
Browser: Can you please give me index.html? I won't mind a compressed version if you can provide that.
Server: I am searching for the file… yes I find it. Wow! You will accept the compressed version That is Amazing. I am zipping it and sending it over.
Browser: Great! It’s only 25 Kb. I’ll unzip it and show it to the user.

Even though the above interaction sounds pretty amusing but this is how it can happen and the pages on internet can now open in a flash. Mod GZIP can compress all outgoing HTML and the browser in return un-compresses the HTML thereby displaying them at faster speeds.
Sometimes issues between browser and proxies can cause a severe mismatch and modules in Apache provide a work around by adding relevant response headers automatically. Servers decide what to gzip based on the file type, for example images and PDF files should not be gzipped because they are already available in a compressed form.
The GZIP compression is therefore an excellent way to reduce the server response time. Through the GZIP compression the response is generally reduced by about 70%. Many popular browsers of today support the GZIP compression.
Here is how you can enable GZIP compression on an Apache server:
1. Make sure you have the deflate module enabled, you can verify this by typing
# /usr/local/apache2/bin/apachectl -t -D DUMP_MODULES
Loaded Modules:
...
deflate_module (static)
...
Syntax OK
2. If you do not have deflate_module then recompile the apache web server to set it on.
3. Add the following code to your Apache conf file
<Location />
SetOutputFilter DEFLATE
BrowserMatch ^Mozilla/4\.0[678] no-gzip\
BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html
# Don't compress images
SetEnvIfNoCase Request_URI \
\.(?:gif|jpe?g|png)$ no-gzip dont-vary
</Location>
Note: The line in bold which goes like.. "no-gzip dont-vary" tells your Apache server to not compress certain type of files.
This is all you need to do to enable GZIP compression.
We hope this benefits you.
Watch out for more . . .
- Log in to post comments
SVN Cheatsheet
This cheatsheet is a quick reference for using SVN,
Create a Repository on Linux: svnadmin create
To store projects in Subversion/SVN, first you must create a repository.
svnadmin create /svnrepos
Add a Project to Repository - svn Import
svn import -m "import project" /home/xxxx/public_html file:///svnrepos/<project name>
Starting SVN Server daemon- svnserve
svnserve -d
This would start the SVN daemon on port 3690. To listen to port other than 3690
svnserve -d --listen-port=8080
Checking Out a Project - svn co
svn co svn://<server>/svnrepos/<project name> svn co stands for svn checkout.
Checking for Changes - svn status
To see what files you have changed or added to your checked out work, use svn status:
svn status
Adding new files - svn add
svn add <file or dir name>
SVN Add Recursively
svn status | grep "^\?" | awk '{print $2}' | xargs svn add
SVN Delete - svn delete
svn delete <file or dir name>
SVN update - svn update
svn update
SVN Commit - svn commmit
svn commit <file or dir name>
You can also use,
svn ci <file or dir name>
SVN Tagging Project
svn copy-m "Tagging the 1.0 release of the project"svn://server-name/svnrepos/project/trunksvn://server-name/svnrepos/project/tags/1.0
excluding file types
Excluding file types methond is missing. I think it is also important to know. Leaving out images, cache files and so on.
SVN Add Recursively
Fri, 05/14/2010 - 23:17 — Anonymous
svn add * --force
Update: To learn about the error SVN add "already under version control",
- Log in to post comments
Drupal Cron Stuck? Log the progress.
Challenge with Drupal 6 Cron
Drupal cron getting stucked is quite a common problem with Drupal 6 and I found out an interesting way to figure out the reason why it is getting stuck.
Logging as always
As always, the solution is to log at the correct place. Drupal cron is invoked at includes/common.inc in the function drupal_cron_run (around line 2727), so we begin here logging into watchdog. We have to start logging when the cron starts for a particular module and when it finishes as follows:
foreach (module_implements('cron') as $module) {
watchdog('cron', t('Cron processing initiated for module: @module.', array('@module' => $module)));
$function = $module .'_cron';
if ($log_timing) {
timer_start($function);
if ($log_timing == 'debug') {
watchdog('cron', t('Cron processing initiated for module: @module.', array('@module' => $module)));
}
}
$function();
if ($log_timing) {
$timer = timer_stop($function);
watchdog('cron', t('Cron time elapsed for @module is @millisecs ms.', array('@module' => $module, '@millisecs' => $timer['time'])));
}
Cron has been running for more than an hour and is most likely stuck.
Also, notice it is quite common that your are getting this message:
"Cron has been running for more than an hour and is most likely stuck."
This means the cron is locked and therefore, we would need to delete the semaphore variable to get the cron to work again.
function drupal_cron_run() {
// If not in 'safe mode', increase the maximum execution time:
variable_del('cron_semaphore');
Now, run http://www.example.com/cron.php and watch your logs.
IMPORTANT NOTE: Don't forget to comment this line from this function after your cron runs successfully.
I had issues with cron run on search module. I skipped search module as follows as everything went well after that.
/**
* Executes a cron run when called
* @return
* Returns TRUE if ran successfully
*/
function drupal_cron_run() {
// If not in 'safe mode', increase the maximum execution time:
variable_del('cron_semaphore');
if (!ini_get('safe_mode')) {
set_time_limit(240);
} // Fetch the cron semaphore
$semaphore = variable_get('cron_semaphore', FALSE);
if ($semaphore) {
if (time() - $semaphore > 3600) {
// Either cron has been running for more than an hour or the semaphore
// was not reset due to a database error.
watchdog('cron', t('Cron has been running for more than an hour and is most likely stuck.'), WATCHDOG_ERROR);
// Release cron semaphore
variable_del('cron_semaphore');
}
else {
// Cron is still running normally.
watchdog('cron', t('Attempting to re-run cron while it is already running.'), WATCHDOG_WARNING);
}
}
else {
// Register shutdown callback
register_shutdown_function('drupal_cron_cleanup');
// Lock cron semaphore
variable_set('cron_semaphore', time());
// Iterate through the modules calling their cron handlers (if any):
// module_invoke_all('cron');
$log_timing = variable_get('cron_log_times', '1');
foreach (module_implements('cron') as $module) {
watchdog('cron', t('Cron processing initiated for module: @module.', array('@module' => $module)));
if ($module == "search") continue;
$function = $module .'_cron';
if ($log_timing) {
timer_start($function);
if ($log_timing == 'debug') {
watchdog('cron', t('Cron processing initiated for module: @module.', array('@module' => $module)));
}
}
$function();
if ($log_timing) {
$timer = timer_stop($function);
watchdog('cron', t('Cron time elapsed for @module is @millisecs ms.', array('@module' => $module, '@millisecs' => $timer['time'])));
}
}
// Record cron time
variable_set('cron_last', time());
watchdog('cron', t('Cron run completed.'), WATCHDOG_NOTICE);
// Release cron semaphore
variable_del('cron_semaphore');
// Return TRUE so other functions can check if it did run successfully
return TRUE;
}
}
Search Cron Handled Separately
In order to run search cron, I wrote another hook_menu function to update search indexes and that worked well. This hook menu was called on cron from linux shell.
<?php
register_shutdown_function('search_update_totals');
// Update word index
foreach (module_list() as $module) {
module_invoke($module, 'update_index');
}
?>
- Log in to post comments
Firefox tips and tricks

I was faced with a annoying problem on Firefox for a couple of days now before my mighty brain discovered a fix.
The zoom size on some of the Firefox pages was getting reset to a value below normal and on every page load I had to hit ctrl+0 to get the page reset to its default size. I resolved this issue by making changes to my Firefox zoom limits.
How I did this?
This was simple. I hit about:config in the URL bar and got the warning as illustrated through the above image.
Clicked on “I'll be careful, I promise!”
Hit the config name in the 'Filter' field and modified the value as follows:
Config name: zoom.maxPercent
Default: 300 (percent)
Modified value: any value higher than 300
Config name: zoom.minPercent
Default: 30 (percent)
Value: any value
Some other tricks that can be achieved through the about:config feature.
1. Increasing Firefox Speed
Config name: network.http.pipelining
Default: False
Modified value: True
Config name: network.http.proxy.pipelining
Default: False
Modified value: True
Config name: network.http.pipelining.maxrequests
Default: 4
Modified value: any value higher than 4, but not more than 8
Config name: network.http.max-connections
Default: 30
Modified value: 96
Config name: network.http.max-connections-per-server
Default: 15
Modified value: 32
2. Increasing and/or Decreasing the amount of Disk Cache
Before increasing the disk cache size, make sure that browser.cache.disk.enabledbrowser.cache.disk.enable is set to True.
Config name: browser.cache.disk.capacity
Default: 50000 (in KB)
Modified value:
0 – disable disk caching
any value lower than 50000 reduces the disk cache
any value higher than 50000 increases the disk cache.
3. Autofill URL in Address Bar
Config name: browser.urlbar.autofill
Default: False
Modified value: True (This would allow firefox to autofill the address as you type in the initial characters in the Address bar)
Keep tracking on this wonder site to get updated on such tips and tricks. Till next. c ya !
- Log in to post comments
Yum has depsolving problems. What to do?

Did you ever try to install an application on CentOS using powerful "yum" and had following errors showing up:
--> Finished Dependency Resolution
rrdtool-1.3.8-2.el5.rf.x86_64 from rpmforge has depsolving problems
--> Missing Dependency: ruby is needed by package rrdtool-1.3.8-2.el5.rf.x86_64 (rpmforge)
Error: Missing Dependency: ruby is needed by package rrdtool-1.3.8-2.el5.rf.x86_64 (rpmforge)
You could try using --skip-broken to work around the problem
You could try running: package-cleanup --problems
package-cleanup --dupes
rpm -Va --nofiles --nodigest
The program package-cleanup is found in the yum-utils package.
The above error implies that yum was trying to install ruby or perl dependency and could not install it because that was excluded in the global exclude in /etc/yum.conf.

The solution is to exclude "perl" or "ruby" or whatever dependecy the system is trying to install in /etc/yum.conf. I simply renamed perl and ruby to something else in the first line of /etc/yum.conf and my "yum install XXXX" wen smooth thereafter.
- Log in to post comments
Enable mod_rewrite module on apache on Ubuntu
If you are using Drupal, clean URLs may not work out of the box on your Ubuntu machine. You would need to enable mod_rewrite module on your apache to do that.
Therefore, first enable the module as follows:
sudo a2enmod rewrite
Change all occurrence of "AllowOverRide None" to "AllowOverRide All". Basically all "None" to "All" in the following file:
sudo vi /etc/apache2/sites-available/default
Restart Apache:
/etc/init.d/apache2 restart
You are done. Your Drupal install should have clean-urls working now.
thanks sunil_ebizon
Thanks for that! This worked on my Ubuntu and now mod rewrite is perfectly working!
hallo Mr. sunil, in ubuntu , it says site offline due to some technical problem , drupal html page coming
Thu, 07/15/2010 - 12:07 — Anonymous
Hai
My name is arun kumar , even the home page is not displaying ,
I did as you said , for rewrite module,
could you tell me where is the error, i spenting a lot of days for it .
I copied the site from windows , to www in ubuntu .
copied the data base to my sql
restareted the apache ,
Done the rewrite module ,
The result is the same
please help , many many thanks if you could solve the problem
- Log in to post comments
hi.its great
Sun, 05/09/2010 - 23:15 — Anonymous
where we have to type this code.
# /usr/local/apache2/bin/apachectl -t -D DUMP_MODULES
Loaded Modules:
...
deflate_module (static)
...
Syntax OK
that one i am not getting and one more thing i can add the follpwing code in my apache server.how it wil get reflet in my service provider server.
<Location />
SetOutputFilter DEFLATE
BrowserMatch ^Mozilla/4\.0[678] no-gzip\
BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html
# Don't compress images
SetEnvIfNoCase Request_URI \
\.(?:gif|jpe?g|png)$ no-gzip dont-vary
</Location>
Thanks Advance,
Regards,
Arthanari.
Great tutorial!
Wed, 06/16/2010 - 16:33 — Anonymous
Very useful tutorial to configure Apache to GZIP compress every page. Here at Kaifu Computing we tend to enable it on a project by project basis, but we are considering configuring our servers as you have spelled out above. Good work!
Tue, 06/22/2010 - 07:23 — Anonymous
<Location />
SetOutputFilter DEFLATE
BrowserMatch ^Mozilla/4\.0[678] no-gzip\
BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html
# Don't compress images
SetEnvIfNoCase Request_URI \
\.(?:gif|jpe?g|png)$ no-gzip dont-vary
</Location>
coach outlet