enable inline editing in jqGrid..

No Comments »

Here is an example to demonstrate how we can enable inline editing in jqGrid. This example is a mixture of ‘Costom Edit’, ‘Using Events’ and ‘Input Types’ examples from jqGrid Demo examples from Mark Williams in MVC (model/view/controller) flavor using PHP Framework CodeIgniter.

You can using any language you want, you just have to do the language specific changes of course.

I have demonstrated how to integrate jqGrid with your code in my last post integrate jqGrid with codeigniter.., please check it first if you are looking for integrating jqGrid on your webpage, the template view and controller/model structures would be the same.

Here I’m using a different table to show the different input types working..

Following is the SQL dump of the table being used.

1
2
3
4
5
6
7
8
9
10
11
12
CREATE TABLE `stetbl` (                 
CREATE TABLE `ebc_group` (                                      
`id` int(11) NOT NULL auto_increment,                         
`name` varchar(255) default NULL,                             
`category` int(11) default NULL,                              
`description` text,                                           
`owner` int(11) default NULL,                                 
`visibility` enum('All','Selected') default 'All',  
`created` datetime default NULL,                              
`approved` enum('Y','N') default 'Y',                         
PRIMARY KEY  (`id`)                                           
)

The front end controller function

1
2
3
4
5
6
7
	function inline_edit_test()
	{
		$data['title'] = "Inline Edit Demo jqGrid | {$this->app_name}";
		$data['main'] = 'edit_test';
		$this->load->vars($data);
		$this->load->view('admin_template');
	}

Your Ad Here

the view to hold the javascript grid code, grid table and pagination div here is edit_test.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?
	$ci =& get_instance();
	$base_url = base_url();
?>
 
<table id="list1"></table>	<!--Grid table-->
<div id="pager1"></div>		<!--Pagination div-->
 
<script type="text/javascript">
var lastsel2;	//save row ID of the last row selected
jQuery().ready(function (){
jQuery("#list1").jqGrid({
   	url:'<?=$base_url.'inline_edit_test'?>',	//Backend controller function generating grid XML
	editurl: '<?=$base_url.'edit_test_save'?>',	//Backend controller function save inline updates
	mtype : "post",		//Ajax request type. It also could be GET
	datatype: "xml",	//supported formats XML, JSON or Arrray
   	colNames:['id','Group Title','Category','Group Description','Group Owner','Created','Visibility','publish','Action'],	//Grid column headings
   	colModel:[
   		{name:'id',index:'id', width:35, align:"left", editable:true, sorttype:'int', editable: true, editrules: { edithidden: true }, hidden: true},
   		{name:'name',index:'name', width:35, align:"left", editable:true, editoptions:{size:'20',maxlength:'255'}},
   		{name:'category',index:'category', width:35, align:"left", search:false},
   		{name:'description',index:'description', width:75, align:"left", editable:true,edittype:'textarea', editoptions:{rows:'2',cols:'50'}},
   		{name:'owner',index:'owner', width:25, align:"left", search:false},
   		{name:'created',index:'created', width:20, align:"left", search:false},
   		{name:'visibility',index:'visibility', width:20, align:"left", editable:true,edittype:'select',editoptions:{value:'All:All;selected:Selected'}, search:false},
   		{name:'approved',index:'approved', width:15, align:"center", editable:true,edittype:'select',editoptions: {value:'Y:Publish;N:Ban'}, search:false},
   		{name:'act',index:'act', width:15, align:"center", editable:false, search:false},
  	],
   	rowNum:100,
   	autowidth: true,
   	height: 300,
   	rowList:[100,200,300,500,800,1000],
   	pager: '#pager1',
	toolbar: [true,"top"],
   	sortname: 'created',
    viewrecords: true,
	gridComplete: function(){
		var ids = jQuery("#list1").getDataIDs();
		for(var i=0;i < ids.length;i++){
			var cl = ids[i];
			se = "<input type='button' value='Save' onclick=\"jQuery('#list1').saveRow('"+cl+"',checksave);\"  />";		//checksave is a callback function to show the response of inline save controller function
			ce = "<input type='button' value='C' title='Cancel' onclick=\"jQuery('#list1').restoreRow('"+cl+"');\" />";
			jQuery("#list1").setRowData(ids[i],{act:se+ce});	//Save and Cancel buttons inserted via jqGrid setRowData function
		}
	},
	onSelectRow: function(id){
		if(id && id!==lastsel2){
			jQuery('#list1').restoreRow(lastsel2);	//restore last grid row
			jQuery('#list1').editRow(id,true);		//show form elements for the row selected to enable updates
			lastsel2=id;	//save current row ID so that when focus is gone it can be restored
		}
	},
    caption:"&nbsp;&nbsp;&nbsp;Inline Edit Example"
}).navGrid('#pager1',{edit:false,add:false,del:false});
 
function checksave(result)
{
	if(result.responseText!='') alert(result.responseText);
	else $("#list1").trigger("reloadGrid");
}

The backend controller function to generate XML feed would be the same as in my last post, except the required changes as we are using a different table here..

And now we need to implement the backend controller function edit_test_save to save the changes as we described in the jqGrid script before. It’s again is pretty simple..

1
2
3
4
5
6
7
8
9
	function edit_test_save()
	{
		if(isset($_POST))
		{
			//model function updateRow writes and executes an UPDATE query with the data supplied
			$r = $this->DB_Func->updateRow('ebc_group',$_POST,array('id'=>$_POST['id'])); //$_POST contains all the editable data when we hit the save button in the grid
			echo $r;
		}
	}

Here the POST array generated by the grid we are passing in the model function updateRow

1
2
3
4
5
id => 1
name => test group
description => test group test group test group test group test group test group test grou...
visibility => All
approved => Y

Again DB_Func here is a model containing a number of SQL query builder functions and updateRow is onw of them. It’s nothing special..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
	function updateRow($table,$data,$where=null)
	{
		$sql = "UPDATE `$table` SET";
		foreach($data as $key => $value)
		{
			$sql .= " `$key`='".mysql_escape_string($value)."',";
		}
		$sql = substr($sql,0,-1);
		if($where!=null)
		{
			$sql .= " WHERE";
			foreach($where as $key => $value)
			{
				$sql .= " `$key`='".mysql_escape_string($value)."' AND";
			}
			$sql = substr($sql,0,-4);
		}
 
		mysql_query($sql);
		if(mysql_error())
		{
			return mysql_error()."<br>$sql";
		}
		return '';
	}

Please feel free to comment and also if you have any suggestions, I’m always ready to learn ;)
Your Ad Here

Posted on May 8th 2010 in codeigniter, jQGrid, jQuery, javascript, php, php frameworks

Want to add Google Street View in your website?

No Comments »

Google street view is a pretty cool widget and also now available for significant amount of areas around the world. It would certainly be very cool to add not only the Google maps in your website but the Google Street view as well. It also is pretty easy to do that, below is all the code you need to add it you just need to know the latitude longitude of the location you want it to show and also it should be on google street view map already of course..

<html>
	<head>
		<title>Google Street View Demo</title>
		<script src="http://maps.google.com/maps?file=api&amp;v=2.x&amp;key=ABQIAAAAp3yqex2QwxZSXQAIGTbL3hQSgN1zkvCdoYVlIYXAwl5r0QbsLBRmauXS9xhCcCs1sTwzbq-Bk3qoZw" type="text/javascript"></script>
		<script>
			function load()
			{
				if (GBrowserIsCompatible())
				{
					var thePano = new GLatLng(latitude_of_your_desired_location,longitude_of_your_desired_location);
					panoramaOptions = { latlng:thePano, userPhotos: false };
					var myPano = new GStreetviewPanorama(document.getElementById("pano"), panoramaOptions);
					GEvent.addListener(myPano, "error", handleNoFlash);
				}
			}
			function handleNoFlash(errorCode)
			{
				if (errorCode == FLASH_UNAVAILABLE)
				{
					return;
				}
			}
			window.onload = load;
			window.onunload = GUnload;
		</script>
	</head>
	<body>
		<div style="margin-left:15px;"><b>Adding Google Street View to the website is super easy..</b></div>
		<div name="pano" id="pano" style="width: 1024px; height: 800px;border:solid #ccc 1px;margin-left:15px;"></div>
	</body>
</html>


Click here for a working demo.

Your Ad Here

Posted on April 25th 2010 in Google Street View, google maps, javascript

Block Adservers to block unnecessary ad blocks and banners for speedy browsing..

No Comments »

if you wanna remove those nasty ads from the pages which waste lot of time and bandwidth then here is something for you I belive it will help you a lot.

how it works

It’s possible to set up a name server as authoritative for any domain you choose, allowing you to specify the DNS records for that domain. You can also configure most computers to be sort of mini-nameservers for themselves, so that they check their own DNS records before asking a nameserver. Either way, you get to say what hostname points to what IP address. If you haven’t guessed already, the way you block ads it to provide bogus information about the domains we don’t want to see – ie, all those servers out there that dedicate their existence to spewing out banner ads.

The hosts file

Probably the most common way people block ads like this is with something called the “hosts file”. The hosts file is a simple list of hostnames and their corresponding IP addresses, which your computer looks at every time you try and contact a previously unknown hostname. If it finds an entry for the computer you’re trying to reach, it sets the IP address for that computer to be whatever’s in the hosts file.

127.0.0.1 is a special IP address which, to a computer, always means that computer. Any time a machine sends a network request to 127.0.0.1, it is talking to itself. This is very useful when it comes to blocking ads, because all we
have to do is specify the IP address of any ad server to be 127.0.0.1. And to do that, all we have to do is edit the hosts file. What will happen then is something like this:

1. you visit a web page

2. the web page contains a banner ad stored on the server “ads.example.com”

3. your computer says “ads.example.com? never heard of it. wait a second, let’s see if I’ve got the number on me…”

4. your computer finds its hosts file and checks to see if ads.example.com is listed

5. it finds the hostname, which points to 127.0.0.1

6. “great”, says the computer, and sends off a request to 127.0.0.1 for the banner ad that’s supposed to be on the page

7. “oh”, says the computer, and fails to show anything because it just sent a request to itself for a banner ad.

So where’s my hosts file?

* Windows 95 / 98 / ME: C:\Windows (I think)

* Windows NT: C:\WinNT\hosts

* Windows 2000: C:\WinNT\system32\drivers\etc\

* Windows XP: C:\Windows\System32\drivers\etc

* FreeBSD / Linux / Mac OS X / Unixish operating systems: /etc/hosts

The format of the hosts file is very simple – IP address, whitespace, then a list of hostnames. However, you don’t need to know anything about the format if you don’t want to as you can just view the list hosts file.

Of course, that’s not the only way to use the list, but it’s probably the most simple for most people.

here is the hosts list (http://blog.anupamgupta.info/res/hosts.txt) which are serving you the ads just append it to your hosts file and enjoy ad free surfing makes things faster. if you want ad from certain site then just remove it from the list.
Your Ad Here

Posted on April 24th 2010 in PCs, computer hacks, computer tutorials, tech hacks

Fixing windows reboot loops and file missing/corrupt problems using Windows recovery

No Comments »

Sometimes Windows XP can act really stupid. I waked up in the morning and started my computer. I worked fine last night and was just looking for checking my mails and all of a sudden I got this message

WINDOWS COULD NOT START BECAUSE THE FOLLOWING FILE IS MISSING OR CORRUPT  = windows\system32\config\system

I thought it was just a little prank XP does all the time and restarted my computer and now bang it just caught into a reboot loop. The windows boot splash shows up for a few seconds and then it restarts the system all over again and again, I was real frustrated and was determined to fix the problems as I had important office documents and other stuff I definitely not wanted to loose.

Upon doing a little research I got a working solution which fixed it up. I’m writing this up as I saw a lot of people searching for straight solution to this problem and very few of the search results I got were useful and helping.

So we can fix it using Windows repair. You may need the WindowsXP installation CD and some idea of DOS copy (http://www.easydos.com/copy.html), delete (http://www.easydos.com/del.html) and rename (http://www.easydos.com/rename.html) commands.

Boot the system to DOS mode or open the recovery console (using the WindowsXP installation CD if available) and make backups of the following files

c:\windows\system32\config\system (to c:\windows\tmp\system.bak)
c:\windows\system32\config\software (to c:\windows\tmp\software.bak)
c:\windows\system32\config\sam (to c:\windows\tmp\sam.bak)
c:\windows\system32\config\security (to c:\windows\tmp\security.bak)
c:\windows\system32\config\default (to c:\windows\tmp\default.bak)

then delete the above files (not the backups!)

then copy the above files from c:\windows\repair to c:\windows\system32\config directory

Assuming that you windows installation is @ c:\windows

Restart your computer, if everything goes right it should fix the problem and start your computer.

However this also have some side-effects as you’ll loose all the driver/software installations and the system will restore to it’s initial install time state so you may have to reinstall all those but all your files would be safe as you didn’t format and reinstall the system.

Hope this would help recovering your system..
Your Ad Here

Posted on April 23rd 2010 in computer hacks, computer tutorials, tech hacks

10 Fast PC Security Enhancements..

No Comments »

Before you spend a dime on security, there are many precautions you can take that will protect you against the most common threats.

1. Check Windows Update and Office Update regularly (_http://office.microsoft.com/productupdates); have your Office CD ready. Windows Me, 2000, and XP users can configure automatic updates. Click on the Automatic Updates tab in the System control panel and choose the appropriate options.

2. Install a personal firewall. Both SyGate (_www.sygate.com) and ZoneAlarm (_www.zonelabs.com) offer free versions.

3. Install a free spyware blocker like SpyBot Search & Destroy. SpyBot is also paranoid and ruthless in hunting out tracking cookies.

4. Block pop-up spam messages in Windows NT, 2000, or XP by disabling the Windows Messenger service (this is unrelated to the instant messaging program). Open Control Panel | Administrative Tools | Services and you’ll see Messenger. Right-click and go to Properties. Set Start-up Type to Disabled and press the Stop button. Bye-bye, spam pop-ups! Any good firewall will also stop them.

5. Use strong passwords and change them periodically. Passwords should have at least seven characters; use letters and numbers and have at least one symbol. A decent example would be f8izKro@l. This will make it much harder for anyone to gain access to your accounts.

6. If you’re using Outlook or Outlook Express, use the current version or one with the Outlook Security Update installed. The update and current versions patch numerous vulnerabilities.

7. Buy antivirus software and keep it up to date. If you’re not willing to pay, try Grisoft AVG Free Edition or Avast free home edition. And doublecheck your AV with the free, online-only scanners available at w*w.pandasoftware.com/activescan and _http://housecall.trendmicro.com.

8. If you have a wireless network, turn on the security features: Use MAC filtering, turn off SSID broadcast, and even use WEP with the biggest key you can get.

9. Join a respectable e-mail security list, such as the one found at http://security.ziffdavis.com, so that you learn about emerging threats quickly and can take proper precautions.

10. Be skeptical of things on the Internet. Don’t assume that e-mail “From:” a particular person is actually from that person until you have further reason to believe it’s that person. Don’t assume that an attachment is what it says it is. Don’t give out your password to anyone, even if that person claims to be from “support.”
Your Ad Here

10 reasons why PCs crash U must Know

No Comments »

Fatal error: the system has become unstable or is busy,” it says. “Enter to return to Windows or press Control-Alt-Delete to restart your computer. If you do this you will lose any unsaved information in all open applications.”

You have just been struck by the Blue Screen of Death. Anyone who uses Mcft Windows will be familiar with this. What can you do? More importantly, how can you prevent it happening?

1) Hardware conflict

The number one reason why Windows crashes is hardware conflict. Each hardware device communicates to other devices through an interrupt request channel (IRQ). These are supposed to be unique for each device.

For example, a printer usually connects internally on IRQ 7. The keyboard usually uses IRQ 1 and the floppy disk drive IRQ 6. Each device will try to hog a single IRQ for itself.

If there are a lot of devices, or if they are not installed properly, two of them may end up sharing the same IRQ number. When the user tries to use both devices at the same time, a crash can happen. The way to check if your computer has a hardware conflict is through the following route:

* Start-Settings-Control Panel-System-Device Manager.

Often if a device has a problem a yellow ‘!’ appears next to its description in the Device Manager. Highlight Computer (in the Device Manager) and press Properties to see the IRQ numbers used by your computer. If the IRQ number appears twice, two devices may be using it.

Sometimes a device might share an IRQ with something described as ‘IRQ holder for PCI steering’. This can be ignored. The best way to fix this problem is to remove the problem device and reinstall it.

Sometimes you may have to find more recent drivers on the internet to make the device function properly. A good resource is www.driverguide.com. If the device is a soundcard, or a modem, it can often be fixed by moving it to a different slot on the motherboard (be careful about opening your computer, as you may void the warranty).

When working inside a computer you should switch it off, unplug the mains lead and touch an unpainted metal surface to discharge any static electricity.

To be fair to Mcft, the problem with IRQ numbers is not of its making. It is a legacy problem going back to the first PC designs using the IBM 8086 chip. Initially there were only eight IRQs. Today there are 16 IRQs in a PC. It is easy to run out of them. There are plans to increase the number of IRQs in future designs.

2) Bad Ram

Ram (random-access memory) problems might bring on the blue screen of death with a message saying Fatal Exception Error. A fatal error indicates a serious hardware problem. Sometimes it may mean a part is damaged and will need replacing.

But a fatal error caused by Ram might be caused by a mismatch of chips. For example, mixing 70-nanosecond (70ns) Ram with 60ns Ram will usually force the computer to run all the Ram at the slower speed. This will often crash the machine if the Ram is overworked.

One way around this problem is to enter the BIOS settings and increase the wait state of the Ram. This can make it more stable. Another way to troubleshoot a suspected Ram problem is to rearrange the Ram chips on the motherboard, or take some of them out. Then try to repeat the circumstances that caused the crash. When handling Ram try not to touch the gold connections, as they can be easily damaged.

Parity error messages also refer to Ram. Modern Ram chips are either parity (ECC) or non parity (non-ECC). It is best not to mix the two types, as this can be a cause of trouble.

EMM386 error messages refer to memory problems but may not be connected to bad Ram. This may be due to free memory problems often linked to old Dos-based programmes.

3) BIOS settings

Every motherboard is supplied with a range of chipset settings that are decided in the factory. A common way to access these settings is to press the F2 or delete button during the first few seconds of a boot-up.

Once inside the BIOS, great care should be taken. It is a good idea to write down on a piece of paper all the settings that appear on the screen. That way, if you change something and the computer becomes more unstable, you will know what settings to revert to.

A common BIOS error concerns the CAS latency. This refers to the Ram. Older EDO (extended data out) Ram has a CAS latency of 3. Newer SDRam has a CAS latency of 2. Setting the wrong figure can cause the Ram to lock up and freeze the computer’s display.

Mcft Windows is better at allocating IRQ numbers than any BIOS. If possible set the IRQ numbers to Auto in the BIOS. This will allow Windows to allocate the IRQ numbers (make sure the BIOS setting for Plug and Play OS is switched to ‘yes’ to allow Windows to do this.).

4) Hard disk drives

After a few weeks, the information on a hard disk drive starts to become piecemeal or fragmented. It is a good idea to defragment the hard disk every week or so, to prevent the disk from causing a screen freeze. Go to

* Start-Programs-Accessories-System Tools-Disk Defragmenter

This will start the procedure. You will be unable to write data to the hard drive (to save it) while the disk is defragmenting, so it is a good idea to schedule the procedure for a period of inactivity using the Task Scheduler.

The Task Scheduler should be one of the small icons on the bottom right of the Windows opening page (the desktop).

Some lockups and screen freezes caused by hard disk problems can be solved by reducing the read-ahead optimisation. This can be adjusted by going to

* Start-Settings-Control Panel-System Icon-Performance-File System-Hard Disk.

Hard disks will slow down and crash if they are too full. Do some housekeeping on your hard drive every few months and free some space on it. Open the Windows folder on the C drive and find the Temporary Internet Files folder. Deleting the contents (not the folder) can free a lot of space.

Empty the Recycle Bin every week to free more space. Hard disk drives should be scanned every week for errors or bad sectors. Go to

* Start-Programs-Accessories-System Tools-ScanDisk

Otherwise assign the Task Scheduler to perform this operation at night when the computer is not in use.

5) Fatal OE exceptions and VXD errors

Fatal OE exception errors and VXD errors are often caused by video card problems.

These can often be resolved easily by reducing the resolution of the video display. Go to

* Start-Settings-Control Panel-Display-Settings

Here you should slide the screen area bar to the left. Take a look at the colour settings on the left of that window. For most desktops, high colour 16-bit depth is adequate.

If the screen freezes or you experience system lockups it might be due to the video card. Make sure it does not have a hardware conflict. Go to

* Start-Settings-Control Panel-System-Device Manager

Here, select the + beside Display Adapter. A line of text describing your video card should appear. Select it (make it blue) and press properties. Then select Resources and select each line in the window. Look for a message that says No Conflicts.
Your Ad Here
If you have video card hardware conflict, you will see it here. Be careful at this point and make a note of everything you do in case you make things worse.

The way to resolve a hardware conflict is to uncheck the Use Automatic Settings box and hit the Change Settings button. You are searching for a setting that will display a No Conflicts message.

Another useful way to resolve video problems is to go to

* Start-Settings-Control Panel-System-Performance-Graphics

Here you should move the Hardware Acceleration slider to the left. As ever, the most common cause of problems relating to graphics cards is old or faulty drivers (a driver is a small piece of software used by a computer to communicate with a device).

Look up your video card’s manufacturer on the internet and search for the most recent drivers for it.

6) Viruses

Often the first sign of a virus infection is instability. Some viruses erase the boot sector of a hard drive, making it impossible to start. This is why it is a good idea to create a Windows start-up disk. Go to

* Start-Settings-Control Panel-Add/Remove Programs

Here, look for the Start Up Disk tab. Virus protection requires constant vigilance.

A virus scanner requires a list of virus signatures in order to be able to identify viruses. These signatures are stored in a DAT file. DAT files should be updated weekly from the website of your antivirus software manufacturer.

An excellent antivirus programme are McAfee VirusScan, Norton AntiVirus Symantec, AVG, Avast.

7) Printers

The action of sending a document to print creates a bigger file, often called a postscript file.

Printers have only a small amount of memory, called a buffer. This can be easily overloaded. Printing a document also uses a considerable amount of CPU power. This will also slow down the computer’s performance.

If the printer is trying to print unusual characters, these might not be recognised, and can crash the computer. Sometimes printers will not recover from a crash because of confusion in the buffer. A good way to clear the buffer is to unplug the printer for ten seconds. Booting up from a powerless state, also called a cold boot, will restore the printer’s default settings and you may be able to carry on.

8 ) Software

A common cause of computer crash is faulty or badly-installed software. Often the problem can be cured by uninstalling the software and then reinstalling it. Use Norton Uninstall or Uninstall Shield to remove an application from your system properly. This will also remove references to the programme in the System Registry and leaves the way clear for a completely fresh copy.

The System Registry can be corrupted by old references to obsolete software that you thought was uninstalled. Use Reg Cleaner by Jouni Vuorio to clean up the System Registry and remove obsolete entries. It works on Windows 95, Windows 98, Windows 98 SE (Second Edition), Windows Millennium Edition (ME), NT4 and Windows 2000.

Read the instructions and use it carefully so you don’t do permanent damage to the Registry. If the Registry is damaged you will have to reinstall your operating system. Reg Cleaner can be obtained from www.jv16.org

Often a Windows problem can be resolved by entering Safe Mode. This can be done during start-up. When you see the message “Starting Windows” press F4. This should take you into Safe Mode.

Safe Mode loads a minimum of drivers. It allows you to find and fix problems that prevent Windows from loading properly.

Sometimes installing Windows is difficult because of unsuitable BIOS settings. If you keep getting SUWIN error messages (Windows setup) during the Windows installation, then try entering the BIOS and disabling the CPU internal cache. Try to disable the Level 2 (L2) cache if that doesn’t work.

Remember to restore all the BIOS settings back to their former settings following installation.

9) Overheating

Central processing units (CPUs) are usually equipped with fans to keep them cool. If the fan fails or if the CPU gets old it may start to overheat and generate a particular kind of error called a kernel error. This is a common problem in chips that have been overclocked to operate at higher speeds than they are supposed to.

One remedy is to get a bigger better fan and install it on top of the CPU. Specialist cooling fans/heatsinks are available from www.computernerd.com or www.coolit.com

CPU problems can often be fixed by disabling the CPU internal cache in the BIOS. This will make the machine run more slowly, but it should also be more stable.

10) Power supply problems

With all the new construction going on around the country the steady supply of electricity has become disrupted. A power surge or spike can crash a computer as easily as a power cut.

If this has become a nuisance for you then consider buying a uninterrupted power supply (UPS). This will give you a clean power supply when there is electricity, and it will give you a few minutes to perform a controlled shutdown in case of a power cut.

It is a good investment if your data are critical, because a power cut will cause any unsaved data to be lost.
Your Ad Here

Posted on April 22nd 2010 in PCs, computer hacks, computer tutorials, tech hacks

Adding scroll effect on local anchors – jQuery

No Comments »

using jQuery tabs I ran into a problem where the #anchor links won’t work in any of the tab content (specially when using Ajax tab load). I had heard of jQuery having a cool scrolling effect to scroll down, up to jump between the #anchor links. Here is how you can add this cool effect on your page..

You have to first either create scroll.js script file with the given javascript code and include it to your html code or just embed it inline using <script> tags..

$(document).ready(function(){
	$(".scroll").click(function(event){
		//prevent the default action for the click event
		event.preventDefault();
 
		//get the full url - like example/page_alias#test
		var full_url = this.href;
 
		//split the url by # and get the anchor target name - home in example/page_alias#test
		var parts = full_url.split("#");
		var trgt = parts[1];
 
		//get the top offset of the target anchor
		var target_offset = $("#"+trgt).offset();
		var target_top = target_offset.top;
 
		//goto that anchor by setting the body scroll top to anchor top
		$('html, body').animate({scrollTop:target_top}, 500);
	});
});


create anchor links you want the scroll effect to initiate on click event. Add class=”scroll” on each link..

<a href="#anchor1" class="scroll">Link One</a>
<a href="#anchor2" class="scroll">Link Two</a>
<a href="#anchor3" class="scroll">Link Three</a>

create span or divs or whatever container element you like with the respective ID you want to jump/scroll into.

    <span id="anchor1">
            Link One related stuff...
            ...
    </span>
    <span id="anchor2">
            Link Two related stuff...
            ...
    </span>
    <span id="anchor3">
            Link Three related stuff...
            ...
    </span>

and that’s it, we are done ;)
Your Ad Here

Posted on April 21st 2010 in ajax, html, jQGrid, javascript

Need explode like function in MySql? You can do it using RegExp.

2 Comments »

Working with a client I had a requirement where a product may belong to multiple categories. Now you can do it by either creating a separate table showing the relation between the two, or you can simply add a new field in the product table and save all the respective categories in a comma separated form.

The problem with the second solution is that you can’t really write a SQL query to retrieve products belonging to a specific category! As there is no php function like explode to do the job for you. Here is an example..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
CREATE TABLE `rbp_products` (
     `id` int(11) NOT NULL AUTO_INCREMENT,
     `name` varchar(255) DEFAULT NULL,
     `image` varchar(55) DEFAULT NULL,
     `description` text,
     `category` text,
     `created` datetime DEFAULT NULL,
     PRIMARY KEY  (`id`)
)
 
INSERT  INTO `rbp_products`(`id`,`name`,`image`,`description`,`category`,`created`) VALUES 
       (1,'test first1234','625301270541172.jpg','Test product description..\r\nTest product description..','1,3,5,8,15,17,25','2010-04-04 07:40:32'),
       (2,'another test1','266381270541206.jpg','another product description..\r\n\r\nanother product description..','1,2,4,6,10,11,18,24,26','2010-04-04 07:41:52'),
       (3,'Sports One','514641270366953.jpg','Sports One test product..','2,4,8,9,11,15,19,24','2010-04-04 07:42:35');


Now I want to search all products belonging to category 11..

suppose $cat_id = 11;

we can try this..

1
SELECT * FROM rbp_products WHERE '{$cat_id}' IN (category)

it looks ok if it was replaced by the category list related to that product which would make it like this for product ID ’1′..

1
SELECT * FROM rbp_products WHERE '{$cat_id}' IN (1,3,5,8,15,17,25)

But it would not work because the expr needs a list of values and we have just issued the category string which obviously is not a list. Since we don’t have explode in MySql we can’t convert it to a list as we do in PHP all the time..

fortunately MySql supports RegExp which is a very strong tool when it comes to string manipulation. We can do it using RegExp, here is how..

1
SELECT DISTINCT * FROM rbp_products WHERE category REGEXP '($cat_id,)|$cat_id$'

so the query would be

1
SELECT DISTINCT * FROM rbp_products WHERE category REGEXP '(11,)|11$'

this means fetch all different products related to category contains ’11,’ or contains only 11 at the end of string i.e. if 11 is not the end of string it must have a comma followed it.

So you can now retrieve all the records related to any specific category easily ;)
Your Ad Here

Posted on April 6th 2010 in MySql, RegExp, php

Google Maps Geocoder in Action..

No Comments »

Ever needed random addresses to be displayed on Google Maps. You can easily achieve the same by using the Google Geocoder. Here is an example..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
<script src="http://maps.google.com/maps?file=api&amp;v=2.x&amp;key=YOUR_GMAP_API_KEY" type="text/javascript"></script>
<script type="text/javascript"> 
	//<![CDATA[
 
	var map = null;
	var geocoder = null;
 
	function load()
	{
		if (GBrowserIsCompatible())
		{
			map = new GMap2(document.getElementById("map"));
			map.setCenter(new GLatLng(DEFAULT_LATITUDE, DEFAULT_LONGITUDE), DEFAULT_ZOOM);
			map.addControl(new GLargeMapControl());
			map.addControl(new GMapTypeControl());
			geocoder = new GClientGeocoder();
			convertToLatLng();
		}
	}
 
	function showAddress(address)
	{
		if (geocoder)
		{
			geocoder.getLatLng(
				address,
				function(point)
				{
					if (!point)
					{
						alert(address + " not found");
					} else {
						map.setCenter(point, 13);
						var marker = new GMarker(point);
						map.addOverlay(marker);
						//marker.openInfoWindowHtml(address);
						//showAddress("118 6th Street, Prince Rupert, British Columbia, Canada");
						//showAddress("1600 Park Avenue, Prince Rupert, British Columbia, Canada");
					}
				}
			);
		}
	}
 
	var addresses = [
		'Full Address 1','Full Address2','...'
	];
	var item_html = [
		'First Address Marker HTML','Second Address Marker HTML','...'
	];
 
	var points = [];
 
	function convertToLatLng()
	{
		if (points.length >= addresses.length)
		{
			showPoints();
		} else {
			geocode(addresses[points.length]);
		}
	}
 
	function geocode(address)
	{
		if (geocoder)
		{
			geocoder.getLatLng(
				address,
				function(point)
				{
					points.push(point);
					window.setTimeout(convertToLatLng, 100);
				}
			);
		}
	}
 
	function createMarker(point, code)
	{
		var marker = new GMarker(point);
		GEvent.addListener(marker, "click", function()
		{
			marker.openInfoWindowHtml(code);
		});
		return marker;
	}
 
	function PopUpMarker(point, address)
	{
		var marker = new Gmarker(point);
		GEvent.addListener(marker, "click", function()
		{
			newwin = window.open(address, 'name', 'width=300,height=200,resizable=1');
		});
		return marker;
	}
 
	function showPoints()
	{
		for (i in points)
		{
			var lat_lng = points[i];
			if (lat_lng)
			{
				map.addOverlay(new GMarker(lat_lng));
				map.addOverlay(createMarker(points[i], item_html[i]));
			}
		}
	}
	window.onload = load;
	window.onunload = GUnload;
 
	//]]>
</script>

Your Ad Here

Posted on March 17th 2010 in ajax, google maps, javascript, php

PHP Random Password Generator

No Comments »

Php random password generator with custom string length and strength..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
function generatePassword($length=9, $strength=0)
{
	$vowels = 'aeuy';
	$consonants = 'bdghjmnpqrstvz';
	if ($strength & 1)
	{
		$consonants .= 'BDGHJLMNPQRSTVWXZ';
	}
	if ($strength & 2)
	{
		$vowels .= "AEUY";
	}
	if ($strength & 4)
	{
		$consonants .= '23456789';
	}
	if ($strength & 8)
	{
		$consonants .= '@#$%';
	}
 
	$password = '';
	$alt = time() % 2;
	for ($i = 0; $i < $length; $i++)
	{
		if ($alt == 1)
		{
			$password .= $consonants[(rand() % strlen($consonants))];
			$alt = 0;
		}
		else
		{
			$password .= $vowels[(rand() % strlen($vowels))];
			$alt = 1;
		}
	}
	return $password;
}

Your Ad Here

Posted on March 17th 2010 in php