April 19, 2010

Simple Constraint Programming Tutorial

A programming language is like a tool. Every tool has a specific purpose. One tool does one job better and another tool does another job better. Programming Languages should be thought of the same way.

Why Constraint Programming

The N-Queens puzzle is very popular and we were able to find several working examples in C and in Prolog.  We analyzed, compiled and tested all these programs and weighed all the pros and cons these two types of languages.

Prolog, being a higher level language, is intuitively easier to understand and easier to program. You can think about the problem with more abstraction. The challenge in actually programming in prolog is that you need to be able to correctly “define” and thus “constrain” the program to do what needs to be done. You don’t have to worry about data types, pointers, data structures and other lower level issues. All the prolog solutions we came across were between 40 and 50 lines of code. On the downside, it was inconvenient when trying to test any n size greater than 12. Trying to solve the puzzle for n=13 takes about 148 seconds.

We found one good example of the n queens problem written in C. We compiled it under Visual Studio 2008, and ran it. The obvious upside in the C program was the speed. It could still solve the puzzle in under a second for n=13. That’s a huge difference compared with the prolog program.  The downside is trying to understand the code and trying to write the code. It’s not as obvious to see what’s happening. The level of abstraction is not as narrow as it is in prolog. On top having to worry about correctly implementing a solution, you have to worry about correctly defining a data structure, defining the correct data types, properly handling arrays and pointers, and other lower level issues not in any way related to the puzzle’s algorithm. The C program that we were testing was 400 lines of code. 236 lines if you remove the comments. That’s almost 5 times the size of the prolog program.

Time Comparisons between Prolog and C

N Prolog (seconds) C (seconds)
1 < 1 < 1
2 < 1 < 1
3 < 1 < 1
4 < 1 < 1
5 < 1 < 1
6 < 1 < 1
7 < 1 < 1
8 < 1 < 1
9 < 1 < 1
10 < 1 < 1
11 3.5 < 1
12 20.3 < 1
13 Too long < 1
14 Too long 1
15 Too long 4
16 Too long 23
17 Too long Too long

Next, we wanted to discuss the simplicity in solving the n-queens problem in prolog. Let’s define our solution for N=4.

We define our solution by stating that each of the 4 queens must occupy it’s very own row, column, downward diagonal, and upward diagonal on a 4×4 board.

And that’s our definition! Now we need to tell prolog to do this and write our constraints.

%% DEFINE OUR BOARD     
%% sq(y-coord, x-coord, downward-diag, upward-diag) 
 sq(1,1,4,1).
 sq(1,2,5,2).
 sq(1,3,6,3).
 sq(1,4,7,4).
 sq(2,1,3,2).
 sq(2,2,4,3).
 sq(2,3,5,4).
 sq(2,4,6,5).
 sq(3,1,2,3).
 sq(3,2,3,4).
 sq(3,3,4,5).
 sq(3,4,5,6).
 sq(4,1,1,4).
 sq(4,2,2,5).
 sq(4,3,3,6).
 sq(4,4,4,7).
 
%% CONSTRAINT
%% We define our solution by stating that
%% each of the 4 queens must occupy it’s
%% very own row, column, downward diagonal,
%% and upward diagonal on a 4x4 board.
 chess(A,B, E,F, I,J, M,N) :-
 sq(A,B,C,D), sq(E,F,G,H), sq(I,J,K,L), sq(M,N,O,P),
 A=1, E=2, I=3, M=4,
 A\=E, A\=I, A\=M,
 B\=F, B\=J, B\=N,
 C\=G, C\=K, C\=O,
 D\=H, D\=L, D\=P,
 E\=I, E\=M,
 F\=J, F\=N,
 G\=K, G\=O,
 H\=L, H\=P,
 I\=M,
 J\=N,
 K\=O,
 L\=P.

Here is our output once we run our program:

?- chess(A,B,E,F,I,J,M,N).
 
A = 1,
B = 2,
E = 2,
F = 4,
I = 3,
J = 1,
M = 4,
N = 3 ;

Which means:  { Q1(1, 2) , Q2(2, 4) , Q3(3, 1) , Q4(4, 3) }

Which is of course, the right solution. Here was the other solution.

A = 1,
B = 3,
E = 2,
F = 1,
I = 3,
J = 4,
M = 4,
N = 2 ;

Which means:  { Q1(1, 3) , Q2(2, 1) , Q3(3, 4) , Q4(4, 2) }

Mapped File, Paging and Memory Protection – C Programming

This program shows use of a number of system calls such as how to map a disk file in the virtual memory of a process space, divide it into pages, set access protection code such as read_only, write_only, etc to individual pages, read/write individual pages, and copy the file back to disk page by page.

#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
extern int errno;
 
main()
{
int fid1, fid2;
void *address1, *address2;
char buf[10], data[10]="edwin c";
char *ptr, *base, data1[10]="baldelomar";
int i, n, pagesize;
struct stat statbuf;
int inFileSize, outFileSize;
 
if ((fid1 = open("alice29.txt", O_RDWR,  0600)) < 0)
 {perror("alice open failed");
  printf (" errno=%d \n", errno); 
 }
 
if (fstat(fid1, &statbuf)<0) perror("fstat error");
inFileSize = statbuf.st_size;
printf("Temp1 file size=%d\n", inFileSize);
 
if ((fid2 = open("temp2", O_RDWR | O_CREAT | O_TRUNC,  0600)) < 0)
 perror("temp2 open failed"); 
 
/* temp2 is empty file. It has no space. Let us make it 20000 bytes
long by setting pointer to 9999 and then writeing a byte. */
if ((lseek(fid2, 19999, SEEK_SET)) < 0) perror ("lseek error");
if (write(fid2, "X", 1) != 1) //write 'X' at end
  {perror("write error"); exit(-1);}
 
 
if (fstat(fid2, &statbuf)<0) perror("fstat error");
outFileSize = statbuf.st_size;
printf("Temp2 file size=%d\n", outFileSize);/*prints size=20000*/
 
/*----------------------------------------------------*/
if ((pagesize=sysconf(_SC_PAGESIZE))<0) perror("sysconf failed");
printf("page size =%d\n", pagesize);
 
/* map source file entirely in memory for reading by possibly
multiple processed, who may share all changes. */
 
if ((address1 = mmap((caddr_t) 0, inFileSize, PROT_READ, MAP_SHARED, fid1, 0))==MAP_FAILED) 
{perror("mmap failed"); printf("errno=%d\n", errno);}
printf("actual mapped address1=0x%x\n", address1);
 
base = ptr = (char *) (address1+500);
for (i=0; i< 8; i++) buf[i] = *ptr++; buf[8]='\0';
printf ("Reading Source: %s\n", buf);
 
/* Following attempt to write to source file should cause segmentation
error, because of read_prot, although the file is onped RDWR.*/
 
/*
ptr = base;
for(i=0; i<8; i++) *ptr++ = data[i]; 
fprintf(stderr, "Writing to source: %s\n", base);
*/
/*----------------------------------------------------*/
if ((address2 = mmap((caddr_t) address1, 10000, (PROT_READ | PROT_WRITE),  MAP_SHARED, fid2, 0))==MAP_FAILED) 
{perror("mmap failed"); printf("errno=%d\n", errno);}
printf("actual address2=0x%x\n", address2);
 
/* Make first page write only */
if ((mprotect(address2, pagesize, PROT_WRITE))<0) printf("protect write error=%d\n", errno);
/* make second page read only. */
if ((mprotect(address2+pagesize, pagesize, PROT_READ))<0) printf("protect read  error=%d\n", errno);
 
 
/* Dump one page of memory space to output file */
if ((msync(address2, pagesize, MS_SYNC))<0) printf("m-sync error=%d\n", errno);
munmap(address1, inFileSize);//remove memory space
munmap(address2, outFileSize);
 
 
/* I/O is possible using file descriptor, but not through alloacted space now. */
close(fid1);
close(fid2);
}

April 12, 2010

Sticky Footer at Bottom of Page using JQuery

I was developing a site for my client and I decided that I wanted to make my footer stick to the bottom of the page regardless of the amount of content. I did a search for “sticky footers” and found some good CSS hacks. The problem is that it’s a little hard to implement once you have a majority of you site structured a specific ways.

I can tell you now that the CSS hacks for a sticky footer doesn’t cooperate well when you have margins declared in other div classes. I spent about an hour trying to get my footer to work right. It would work well in some pages but in others, would display a vertical scroll bar with 20 pixels or so left to scroll.

I got fed up and decided to try and use JQuery to solve my problems. It worked brilliantly! And it’s as simple as this. If my window height is greater than my content plus footer height, add the appropriate top padding to the footer that will keep it always on the bottom. If the content height is greater than the windows height, leave the padding as it was previously declared in your css. And just make sure you calculate the top padding on page load and when the window is resized.

Sticky Footer

Here is the code. Just put it at the end of your page somewhere. Make sure you change the class name ‘.footer’ with whatever class or id name you are using for your footer.

$(function(){
	positionFooter(); 
	function positionFooter(){
		var padding_top = $(".footer").css("padding-top").replace("px", "");
		var page_height = $(document.body).height() - padding_top;
		var window_height = $(window).height();
		var difference = window_height - page_height;
		if (difference < 0) 
			difference = 0;
 
		$(".footer").css({
			padding: difference + "px 0 0 0"
		})
	}
 
	$(window)
		.resize(positionFooter)
});

April 8, 2010

Turn Off Autocomplete in Aptana Studio

I had the hardest time trying to figure out how to turn off autocomplete in Aptana Studio. Which means only two things: That turning off autocomplete is very straightforward and obvious and it just took me a long time to figure it out. Or that no one has gone to the effort to explain how to do it. I’m assuming and hoping for the latter. Here’s how:

Window->Preferences->Web->HTML Files->Editor->Typing

And then uncheck everything. You should be good to go.

What Width Should I Make my Website?

You have two options when it comes to deciding what width to make your website. You can have it expand the whole width of the viewers browser. Or you can have it set at a fixed size. Even if you have your page expanding the whole width of the browser, you’ll have to decide on a minimum width for your display to set to.

Personally, I cater towards a screen size of 1024 x 768. The web page you are viewing now has a fixed width of 900 pixels. Here is a list of widths of what other websites are using:

Name Website Width
Facebook facebook.com 980px
Yahoo yahoo.com 990px
MSN msn.com 970px
New York Times nytimes.com 970px
Wikipedia wikipedia.com 100%
Web Krunk webkrunk.com 985px
WalMart walmart.com 720px
NFL nfl.com 985px
Best Buy bestbuy.com 790px
Apple apple.com 985px

Here are some statistics on screen size usage from w3schools.com

Date Higher 1024×768 800×600 640×480 Unknown
January 2010 76% 20% 1% 0% 3%
January 2009 57% 36% 4% 0% 3%
January 2008 38% 48% 8% 0% 6%
January 2007 26% 54% 14% 0% 6%
January 2006 17% 57% 20% 0% 6%
January 2005 12% 53% 30% 0% 5%
January 2004 10% 47% 37% 1% 5%
January 2003 6% 40% 47% 2% 5%
January 2002 6% 34% 52% 3% 5%
January 2001 5% 29% 55% 6% 5%
January 2000 4% 25% 56% 11% 4%

More specific screen resolution statistics from w3schools.com.

January 2010
Resolution % of Total
1280×1024 18.2 %
1280×800 17.3 %
1440×900 10.5 %
1680×1050 10.0 %
1920×1200 4.6 %
1366×768 3.6 %
1920×1080 2.3 %
1152×864 2.1 %
1600×1200 1.4 %
1280×768 1.2 %
Other 4.8 %

April 6, 2010

How to Select Field Names in Table in CakePHP

In php you can use mysql_field_name to get the field name of the specified field in a result. Someone asked me the following question.

If Employee table has three rows id,name and address. How do we fetch those names (id,name,address) using sql query in cakephp?

First of all, you can’t actually use mysql_field_name() in cakephp. But there are workarounds. Say you want to find the field names of the the table ‘Post’. Here is what you can do.

$array = $this->Post->find('all');
 
$array = Set::extract('/0/Post', $array);
pr($array);
 
$field_names = array_keys($array[0]['Post']);
pr($field_names);

The result of the print statements will display the following

Array
(
    [0] => Array
        (
            [Post] => Array
                (
                    [id] => 2
                    [title] => A title once again
                    [body] => And the post body follows.
                    [created] => 2010-02-08 07:48:03
                    [modified] => 
                )
 
        )
 
)
 
Array
(
    [0] => id
    [1] => title
    [2] => body
    [3] => created
    [4] => modified
)

I hope this helps. Feel free to comment on this page. I’ll get notified immediately.

Web Krunk, Thanks for the Great Blogging Tips You Provide!

I just wanted to give thanks to Web Krunk for providing very useful information regarding blogging and Search Engine Optimization. Because of Web Krunk, I’ve been able to:

  1. Dramatically increase the rate at which Google crawls my site. Before, Google crawled my site once a month. But Web Krunk provided me with great tips and now Google crawls my site immediately after I post new articles.
  2. I was also able to achieve a higher ranking in Google’s organic search for certain keywords vital to the success of my business.
  3. I have a better understand now on how to use twitter and certain wordpress plugins to increase my traffic.

Blogging is one of the best ways for anyone to get ahead of the curve. I never ever pictured myself blogging. But there is a lot power in it if you can utilize it correctly. If you are new to blogging, check out webkrunk.com. It is really helping me to bring more traffic to my site.

Also, if you know of any other good blogging sites out there, leave a comment. I would love to check it out.

April 4, 2010

Add a Title to Your Blog Homepage in WordPress

I came across an interesting problem. When you create a WordPress site and your blog page is you home page, there is no editable page in your administration dashboard. Normally, your title tag in WordPress looks like this:

<title>
    <?php wp_title('&laquo;', true, 'right'); ?> 
    <?php bloginfo('name'); ?>
</title>
 
/*
* This Generates:
* <title>
*     Your Blog Name
* </title>
*
* when you are at you home page. And:
*
* <title>
*     Your Post Title « Your Blog Name
* </title>
*
* when you are on a post page
*/

The problem is that wp_title() doesn’t have any title to return because your blog page isn’t an editable page in your dashboard. Here is a small hack to get it to work. You will need to make sure to fill out your tagline in Administration->Settings->General->Tagline. This input will act as your title.

<title>
    <?php if (is_home()) : 
        bloginfo('description'); 
        echo " &laquo; "; 
    else : 
        wp_title('&laquo;', true, 'right'); 
    endif;?> 
    <?php bloginfo('name'); ?>
</title>
 
/*
* This Generates:
* <title>
*     Your Tagline Description « Your Blog Name
* </title>
*
* when you are at you home page. And:
*
* <title>
*     Your Post Title « Your Blog Name
* </title>
*
* when you are on a post page
*/

10 Things Your Website Must Have

  1. A well designed, simple, and scalable logo. Your logo is the heart and soul of your organization. Your website should be designed around the style of your logo. If you want to see what really good logos look like, click here.
  2. Unique, well-written, and fresh content. Useful content gives visitors an incentive to return and refer others.
  3. You feel safe and secured buying a computer from Apple. How you present your website is extremely important.
  4. Simple and obvious website navigation. Make sure your visitors are not getting lost.
  5. A great domain name. A simple and easy-to-remember domain name will help you to build your brand and retain loyal visitors.
  6. Pleasant and simple cross-browser-compatible design. It is important to make sure that your website is accessible for all users regardless of the browser or monitor that is used to view it.
  7. High quality images. Poor quality images will make your website appear amateur.
  8. Fast-loading pages. In the first few seconds of visiting your website, a visitor decides to stay or go. It is important that you site loads quickly enough for them to view your website and make the decision for themselves.
  9. Unique titles, headlines, and meta descriptions for each page. Titles, descriptions, and headlines are important to search engine optimization. This is so critical for the success of your organization. There’s no point in having a good looking website if no one can find it.
  10. Contact information or a contact form. It is a great idea to display contact information because it inspires trust. As an alternative, you can also provide a contact form which is a great way to capture leads, get feedback, or provide visitors with an easy way to contact you.
  11. Custom error pages. Without fail, visitors will visit pages that do not exist. Perhaps an external website linked to a wrong page. Or maybe they mistakenly entered a url in their browser. By creating custom error pages, you can provide your users with a seamless user experience and provide them quick access to whatever they are looking for.

April 3, 2010

What is the Best Text Editor for Web Development?

I have been developing websites for 7 years now, and I’ve gone through so many text editors in my quest for finding the perfect text editor. I will go through now and give you my opinion on all the text editors I’ve used. Let me say now that this review are for the programmers who hard code every single line and pixel.

Dreamweaver Logo
Dreamweaver was the first IDE I ever used for developing websites. It has a nice color scheme and the ftp support is very solid. The only draw back is that it can be a little slow at times to upload and download files. Dreamweaver supports auto-upload on save command. It also nicely synchronizes all your server files with your local files. It feels good to know that I always have the latest back up of my website. What I don’t like about it is that it’s a very heavy program. It’s designed not just for coders, but also for designers. There are more configuration options than I care to think about. It’s also a very expensive piece of software.

Notepad++ Logo
Next comes Notepad++. This text editor is so close to being the perfect text editor. If it had a better ftp plugin, I would give this editor a grade of a 100. Sadly though, the ftp plugin is quite annoying. First, if you are editing a file for more than 15 minutes without using the ftp, the plugin will automatically disconnect and collapse your tree structure. I get quite a few errors when trying to run general operations like save or download. There have been a few times where the ftp plugin lost some of my files. When downloading, it would download 80% of the file without displaying an error. So if I was editing code somewhere along the top, and a uploaded the file back to the server, I would lose the bottom 20% percent. If you have WAMP server and you are coding locally, Notepad++ is perfect. But if you have to edit files through ftp, It can be a little frustrating.

Aptana Studio Logo
Next comes Aptana Stuido. I was very excited when I heard and read about Aptana. First, their ftp support is very good. I can actually open up multiple ftp sites, and drag and drop files between them. It also has nice CSS support like Dreamweaver. The downside is that it’s written in JAVA. Not to say there is anything wrong with JAVA applications, but it can be a little slow at times. Sometimes, I feel like there is a small delay between my keystrokes and the text display. It’s not the most stable program and Aptana has crashed enough for me to make that comment. Sometimes, the FTP can be slow and I just end up using Filezilla to transfer images and videos. It’s a bit of a hassel to set up at first because you have to install the PHP and JQuery packages in order to start editing files. But, I’m just being really picky. Aptana is still a good Web Development IDE and it’s the application I use when I develop websites on Windows. Although, it’s definitely not my default text editor. It’s still a little too heavy to get that kind of treatment. Notepad++ gets that award.

Coda Logo
Finally we have Coda! It’s just a beautiful text editor. It’s lightweight, but at the same time, you can do so much with it. It’s FTP support is fast and stable. It almost feels like I’m browsing a local directory. I just get things done faster when working in Coda, and I also feel happier. This is the difference between free open source software and paying for software. Coda cost a $100 to use. But it’s true that you get what you pay for. All the other text editors listed above are free. Also take note that Coda is only for Mac OS.

Which now brings up another question. Should you develop websites on a Mac or a Windows PC?

Honorable Mentions

Gedit Logo
Gedit – Gedit is for linux. I feel like I spend more time trying to customize it and make it my perfect text editor than actually programming on it. But it’s very good.

UltraEdit Logo
UltraEdit – This text editor is not free. But it’s pretty good. I didn’t actually purchase it because Aptana could do everything I needed to do while still being free. UltraEdit is like Notepad++, but with better support.