Friday, October 10, 2008

PHP Cheat Sheets

Cheat Sheet Index

How to make a CSS menu

Standards Compliant Menu

A menu is nothing more than a list of links for navigation, so the most ideal way to code your menus are by using a list, styled with CSS. This makes the styling ability very flexible while keeping the content-end of the list completely separate from any styling and in a format that is easy to read when style sheets are not in use or disabled.

First thing we need to do is build the list of links using the unorderd list tag as follows:


PHP short-hand IF statement

Lightweight IF Syntax

Any programmer will agree that the IF/ELSE statements are a fundamental part of any language. The basic syntax is pretty universal between languages but many dont realise that there is a shorthand version that allows switching to be done inline.

The syntax is simply statement ? if-true : if-false

$variable = (statement) ? "return if true" : "return if false";

Compared to

if(statement) {
$variable = "return this if true";
else {
$variable = "return this if false";

As you can see, you save a lot of coding by using this lightweight syntax for simple IF/ELSE statements. It can also be used inline within strings which is where I find the most benefit of using it. Here is an example that has a real world use for a simple output that changes between "there is 1 item", "there are X items", and "there are no items" using multiple statements.

$text = "There ".
($total==1 ? "is 1 item" :
"are ".($total == 0 ? "no items" : "$total items")

Compared to:

if($total==0) {
$text = "There are no items";
else if($total==1) {
$text = "There is 1 item";
else if($total > 0) {
$text = "There are $total items";

Wednesday, March 26, 2008

Validation with Regular Expression

Some useful Validation with Regular Expression here

  • Not empty = '/.+/'
  • Numbers [0-9] = '/^[-+]?\\b[0-9]*\\.?[0-9]+\\b$/'
  • A valid email address = '/\\A(?:^([a-z0-9][a-z0-9_\\-\\.\\+]*)@([a-z0-9][a-z0-9\\.\\-]{0,63}\\.
  • A valid year (1000-2999) = '/^[12][0-9]{3}$/'
  • Credit Card : 'amex' => '/^3[4|7]\\d{13}$/'
    'bankcard' => '/^56(10\\d\\d|022[1-5])\\d{10}$/'
    'diners' => '/^(?:3(0[0-5]|[68]\\d)\\d{11})|(?:5[1-5]\\d{14})$/'
    'disc' => '/^(?:6011|650\\d)\\d{12}$/'
    'electron' => '/^(?:417500|4917\\d{2}|4913\\d{2})\\d{10}$/'
    'enroute' => '/^2(?:014|149)\\d{11}$/'
    'jcb' => '/^(3\\d{4}|2100|1800)\\d{11}$/'
    'maestro' => '/^(?:5020|6\\d{3})\\d{12}$/'
    'mc' => '/^5[1-5]\\d{14}$/'
    'solo' => '/^(6334[5-9][0-9]|6767[0-9]{2})\\d{10}(\\d{2,3})?$/'
    'switch' => '/^(?:49(03(0[2-9]|3[5-9])|11(0[1-2]|7[4-9]|8[1-2])|36[0-9]{2})\\d{10}(\\d{2,
    'visa' => '/^4\\d{12}(\\d{3})?$/'
    'voyager' => '/^8699[0-9]{11}$/'
    'fast' => '/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|3(?:0[0-5]|[68][0-9])
  • url = '/^(?:(?:https?|ftps?|file|news|gopher):\\/\\/)?(?:(?:(?:25[0-5]|2[0-4]\d|(?:(?:1\d)?
i collected some source ... try..

how to write a Regular Expression

What Regular Expression?
A regular expression is a pattern that can match various text strings, used for validations.

Where and when to use Regular Expression?
It can be used in the programming languages which supports or has regular expression class as in built or it supports third party regular expression libraries.

Regular expressions can be used to valid different type of data without increase the code with if and case conditions. A number of if conditions can be omitted with single line of regular expression checking.

Benefits of Regular Expression:
The following are benefits (not all included) of use of Regular Expression.
a) # line of code can be reduced.
b) Speed Coding.
c) Easy maintenance (you don’t need to change if validation criteria changes, just check the regular expression string).
d) Easy to understand (you don’t need to understand the programmer logic on large if statements and case statements).

Elements of Regular Expression:
Here are the basic elements of regular expression characters/literals, which can be used to build big regular expressions:

^ ---->Start of a string.
$ ---->End of a string.
. ----> Any character (except \n newline)
{...}----> Explicit quantifier notation.
[...] ---->Explicit set of characters to match.
(...) ---->Logical grouping of part of an expression.
* ---->0 or more of previous expression.
+ ---->1 or more of previous expression.
? ---->0 or 1 of previous expression; also forces minimal matching when an expression might match several strings within a search string.
\ ---->Preceding one of the above, it makes it a literal instead of a special character. Preceding a special matching character, see below.
\w ----> matches any word character, equivalent to [a-zA-Z0-9]
\W ----> matches any non word character, equivalent to [^a-zA-Z0-9].
\s ----> matches any white space character, equivalent to [\f\n\r\v]
\S----> matches any non-white space characters, equivalent to [^\f\n\r\v]
\d ----> matches any decimal digits, equivalent to [0-9]
\D----> matches any non-digit characters, equivalent to [^0-9]

\a ----> Matches a bell (alarm) \u0007.
\b ----> Matches a backspace \u0008 if in a [] character class; otherwise, see the note following this table.
\t ---->Matches a tab \u0009.
\r ---->Matches a carriage return \u000D.
\v ---->Matches a vertical tab \u000B.
\f ---->Matches a form feed \u000C.
\n ---->Matches a new line \u000A.
\e ---->Matches an escape \u001B

$number ----> Substitutes the last substring matched by group number number (decimal).
${name} ----> Substitutes the last substring matched by a (? ) group.
$$ ----> Substitutes a single "$" literal.
$& ----> Substitutes a copy of the entire match itself.
$` ----> Substitutes all the text of the input string before the match.
$' ----> Substitutes all the text of the input string after the match.
$+ ----> Substitutes the last group captured.
$_ ----> Substitutes the entire input string.

(?(expression)yes|no) ----> Matches yes part if expression matches and no part will be ommited.

Simple Example:
Let us start with small example, taking integer values:
When we are talking about integer, it always has fixed series, i.e. 0 to 9 and we will use the same to write this regular expression in steps.

a) Regular expression starts with “^”
b) As we are using set of characters to be validated, we can use [].
c) So the expression will become “^[1234567890]”
d) As the series is continues we can go for “-“ which gives us to reduce the length of the expression. It becomes “^[0-9]”
e) This will work only for one digit and to make it to work for n number of digits, we can use “*”, now expression becomes “^[0-9]*”
f) As with the starting ending of the expression should be done with “$”, so the final expression becomes “^[0-9]*$”

Note: Double quotes are not part of expression; I used it just to differentiate between the sentences.

Is this the way you need to write:
This is one of the way you can write regular expression and depending on the requirements and personal expertise, regular expression could be compressed much shorter, for example above regular expression could be reduced as.

a) Regular expression starts with “^”
b) As we are checking for the digits, there is a special character to check for digits “\d”
c) And digits can follow digits , we use “*”
d) As expression ends with “$”, the final regular expression will become

Digits can be validated with different ways of regular expressions:

1) ^[1234567890]*$
2) ^[0-9]*$
3) ^\d*$

Which one to choose?
Every one of above expressions will work in the same way, choose the way you are comfort, it is always recommended to have a smaller and self expressive and understandable, as these will effect when you write big regular expression.

Example on exclude options:
There are many situation which demands us to exclude only certain portion or certain characters,
Eg: a) Take all alpha numeric and special symbols except “&”
b) Take all digits except “7”
then we cannot prepare a big list which includes all instead we use the symbol of all and exclude the characters / symbols which need to be validated.
Eg: “^\w[^&]*$” is the solution to take all alpha numeric and special symbols except “&”.

Other Examples:
a) There should not be “1” as first digit,?
^[^1]\d*$ ? this will exclude 1 as first digit.

b) There should not be “1” at any place?
^\d[^1]*$ ? this will exclude the 1 at any place in the sequence.

Note: Here ^ operator is used not only to start the string but also used to negate the values.

Testing of Regular expression:
There are several ways of testing this
a) You can write a windows based program.
b) You can write a web based application.
c) You can even write a service based application.

Windows base sample code:
Here are steps which will be used for regular expression checking in dotNet:

a) Use System.Text.RegularExpression.Regex to include the Regex class.
b) Create an Regex object as follows:
Regex regDollar= new System.Text.RegularExpressions.Regex("^[0-9]*$ ");
c) Call the IsMatch(string object) of the Regex call, which will return true or flase.
d) Depending on the return state you can decide whether passed string is valid for regular expression or not.]

Here is the snap shot code as function:

Public boolean IsValid(string regexpObj, string passedString)
//This method is direct method without any exceptional throwing..
Regex regDollar= new System.Text.RegularExpressions.Regex(regexpObj);
return regDollar.IsMatch(passedString);

With minor changes to the above function it can be used in windows or webbased or even as a service.
source :

Thursday, March 13, 2008

Downloading Files From MySQL Database

Downloading Files From MySQL Database

When we upload a file to database we also save the file type and length. These were not needed for uploading the files but is needed for downloading the files from the database.

The download page list the file names stored in database. The names are printed as a url. The url would look like download.php?id=3. To see a working example click here. I saved several images in my database, you can try downloading them.

more info:

Uploading Files To MySQL Database

More info :

Using PHP to upload files into MySQL database sometimes needed by some web application. For instance for storing pdf documents or images to make som kind of online briefcase (like Yahoo briefcase).

For the first step, let's make the table for the upload files. The table will consist of.

  1. id : Unique id for each file
  2. name : File name
  3. type : File content type
  4. size : File size
  5. content : The file itself

For column content we'll use BLOB data type. BLOB is a binary large object that can hold a variable amount of data. MySQL have four BLOB data types, they are :

  • BLOB

Since BLOB is limited to store up to 64 kilobytes of data we will use MEDIUMBLOB so we can store larger files ( up to 16 megabytes ).


More info :

Monday, March 10, 2008

A Step-by-Step Guide To Using MySQL with ASP.NET

Many people have asked me for this tutorial, so here goes.

For those of you who don't know, MySQL is an open-source DataBase server. Being that it's open-source, it's also free. That's about as low-cost as you can get. Of course, you may ask 'Why use MySQL'? Did you read the previous sentences?? It's free, as well as being a fairly robust database server!

To be able to use MySQL, there are a couple of downloads that must be done:

  1. MySQL Itself
  2. MySQL ODBC Driver
The Database Server (MySQL), itself can be downloaded here:

The Driver (for Windows) can be downloaded here:

The biggest hurdle in using MySQL, is the setup - much like many other users of MSDE have found out. Without a user interface, it's quite cumbersome, requiring a command prompt to do all the work. Here's the best page I've found so far to take you, step-by-step through this process:

Now, once this is all set up - guess what - you have no data. If you want, the above installation page will also help you get started creating databases, tables and fields for your sample data. But, if you want a much quicker way to populate your database server, so you can get started, AugustWind Software has user interface for MySQL called Data Management Toolkit. Check it out here

Now - the part you actually came here for - - the easy part!

On other parts of this site, you've seen many samples, using MS Access and SQL Server. As you might have noticed, there are only three major differences in using these.

  1. Namespaces used
  2. Connection String
  3. Prefix to data classes (like: OleDbDataAdapter vs. SQLDataAdapter, specific to the Imported Namespaces
For MySQL, the driver which you downloaded (above), is an ODBC Driver, therefore, numbers 1 and two in the above list use 'ODBC':
<%@ Import Namespace="System.Data.ODBC" %>
And, you use classes like ODBCDataAdapter, ODBCDataReader, ODBCCommand, etc.

To finish out the three items in the above list, here, we show you the Connection String needed:

"Driver={MySQL ODBC 3.51 Driver};uid=YourUID;password=YourPWD;Server=YourServerIP;Option=16834;Database=YourDB;"
or, you can use:
Just change these few things, in your code, and you're off and running, using MySQL in your own ASP.Net documents!

Now, do you believe me, when I say that using MySQL in your ASP.Net documents is the easy part? In fact, if you have a hosted web site, chances are, most of the setup can be done by someone else and all you will need to do is the pages themselves!

Now, you can't put off using MySQL, for lack of knowledge!

To see a full code sample, check out this page:
To see a code sample with ASP.Net 2.0, check out:

Thursday, March 6, 2008

In and out of PHP before they even knew what hit 'em

When embedding PHP within HTML, you can close your PHP tag whenever you want to output HTML. This enables speedier processing of your PHP. For instance:

Hey Turkeys! Behind ya!

I just drop by with present for warming of house, instead find you grappling with

Hopefully that last one didn't confuse you as much it confused me, the example is a bit extreme. However look over it a few times and you will understand exactly what is going on.

They true did false, they were the trueiest bunch of falses that ever trued

If all you are trying to test for is a boolean (true/false) of a variable or function then instead of laying down a bunch of code like this:

if ($blackbeard == true) echo 'Arr, this chair be high, says I.';
elseif ($seacaptain == false) echo 'Yar, I'm not attractive.';

You can omit == and != with:

if ($blackbeard) echo 'Arr, this chair be high, says I.';
elseif (!$seacaptain) echo 'Yar, I'm not attractive.';

This same format can apply to functions and multiple conditions. For example:

if ($benedict_arnold != true && strpos($photo,'map') == true)
echo 'You idiot, you can't read!';

if (high_chair($blackbeard) == false)
echo 'Aye, 'tis true. My debauchery was my way of compensating.';

The following is the same exact statement (except with less code):

if (!$benedict_arnold && strpos($photo,'map'))
echo 'You idiot, you can't read!';

if (!high_chair($blackbeard))
echo 'Aye, 'tis true. My debauchery was my way of compensating.';

One control structure to rule them all, One constant to find them, One set of conditional brackets to bring them all and in the darkness bind them

Not anymore! If you have a single expression following a control structure, you do not need to waste your time with brackets { }.

if ($gollum == 'halfling') {
$height --;

Is the same as:

if ($gollum == 'halfling') $height --;

This can be applied to any control structure statement. For example:

if ($gollum == 'halfling') $height --;
else $height ++;

if ($frodo != 'dead')
echo 'Gosh darnit, roll again Sauron';

foreach ($kill as $count)
echo 'Legolas strikes again, that makes' . $count . 'for me!';

The fewer brackets you have cluttering up your code, the easier it may be to read.

Single Quotes versus Double Quotes

Any time you put something in "double" quotes, you are asking PHP to check that content for a variable. So even though the following lines do not contain variables within the double quotes, PHP will still waste precious computing time scanning them anyway.

$mytext = "Dental Plan";
if ($mytext == "Dental Plan") {
echo "Lisa needs braces"; }

Those same three lines of code could be executed much faster if 'single' quotes were used in place of "double" quotes.

$mytext = 'Dental Plan';
if ($mytext == 'Dental Plan') {
echo 'Lisa needs braces'; }

Now that may not seem like much, but having PHP check for variables where it doesn't need to over the course of a larger script, can certainly impede run-time. Just to clarify my point, PHP will not read a variable if it is within 'single' quotes.

echo '$mytext, Lisa needs braces.';
// Will output: $mytext, Lisa needs braces.
echo "$mytext, Lisa needs braces.";
// Will output: Dental Plan, Lisa needs braces.

What is the the super-secret of keeping those scripts speeding along the rusty pipes of your server? Avoid double quotes at all costs. Even if you are working with a variable and think you need double quotes, it is more efficient for PHP to execute this:

echo $mytext . 'Lisa needs braces.';

As opposed to this bit of molasses-like code:

echo "$mytext Lisa needs braces.";

It All Adds Up

$variable = $variable + 1;

Is the same as:

$variable ++;

This method also works for subtraction:

$variable --;

You can also apply a similar method for concocting strings. So instead of:

$mytext = 'Done and Done.';
$mytext = "$mytext And I mean Done!"; // $mytext = 'Done and Done And I mean Done!';

Use this shorthand method of adding another string of text onto the end of the first string:

$mytext = 'Done and Done.';
$mytext .= ' And I mean Done!'; // $mytext = 'Done and Done And I mean Done!';

Saturday, February 16, 2008

Object Oriented Concepts - Difference between generalization and realization

Generalization connects a sub-class to a super-class. It’s another name for inheritance. Realization connects a class to an interface. It’s another name for implementation.

Generalization is equivalent to public inheritance in C++ or ‘extends’ in java. It implies inheritance of interface and implementation.

Realizes is equivalent to ‘implements’ in java. It represents conformance to an interface as opposed to inheriting anything.

Object Oriented Analysis Design OOAD Tips

Object Oriented Basics Concepts Fundamentals

Inheritance in Programming Languages

Object Oriented Programming Advantages Disadvantages

CMM software

Java Programming Interview Questions

  • Can you load server object dynamically? If so what are 3 major steps involved in it?
  • Can you run product development on all operating systems?
  • Considering notepad/IE or any other thing as process, What will happen if you start notepad or IE 3 times ? Where three processes are started or three threads are started?
  • Difference : AWT and Swing?
  • Difference : Abstract class and Interface?
  • Difference : Grid and Gridbaglayout?
  • Difference : Process and Thread?
  • Difference : java and c++?
  • Difference : process and threads?
  • Does java support function overloading, pointers, structures, unions or linked lists?
  • Does java support multiple inheritance? if not, what is solution?
  • Explain 2-tier and 3-tier architecture?
  • Explain about version control?
  • Have you ever used HashTable and Directory?
  • How can two threads be made to communicate with each other?
  • How can we do validation of fields in project?
  • How can you know about drivers and database information ?
  • How do you download stubs from Remote place?
  • How does thread synchronization occur in monitor?
  • How java can be connected to database?
  • How will you add panel to frame?
  • I want to store more than objects in remote server? Which methodology will follow?
  • In container there are 5 components. I want to display all component names, how will you do that?
  • In htm form I have button which makes us to open another page in seconds. How will you do that?
  • In htm page form I have one button which makes us to open new page in seconds. How will you do that?
  • Is there any tag in htm to upload and download files?
  • Meaning of Servelet? What are parameters of service method?
  • Meaning of Session? Explain something about HTTP Session Class?
  • Meaning of Static query and Dynamic query?
  • Meaning of class loader? How many types are there? When will we use them?
  • Meaning of cookies? Explain main features?
  • Meaning of distributed application? Why are we using that in our application?
  • Meaning of flickering?
  • Meaning of function overloading and function overriding?
  • Suppose if we have variable ‘I’ in run method, if I can create one or more thread each thread will occupy separate copy or same variable will be shared?
  • Tell some latest versions in JAVA related areas?
  • What are JVM.JRE, J2EE, JNI?
  • What are Normalization Rules? Define Normalization?
  • What are abstract classes?
  • What are adapter classes?
  • What are advantages of java over C++?
  • What are benefits if Swing over AWT?
  • What are byte codes?
  • What are files generated after using IDL to java compiler?
  • What are session variable in servlets?
  • What are statements in Java?
  • What are streams?
  • What are swing components?
  • What are traverses in binary tree?
  • What are virtual functions?
  • What do you know about garbage collector?
  • What do you mean by light weight and heavy weight components?
  • What do you mean by multithreading?
  • What is JAR file?
  • What is JFC?
  • What is JNI?
  • What is base class for all swing components?
  • What is client server computing?
  • What is constructor and virtual function? Can we call virtual function in constructor?
  • What is corresponding layout for card in swing?
  • What is difference abstract class and interface?
  • What is exact difference in between Unicast and Multicast object? Where will it be used?
  • What is functionability stubs and skeletons?
  • What is functionality of stub?
  • What is interface?
  • What is layout for toolbar?
  • What is light weight component?
  • What is main functionality of Prepared Statement?
  • What is main functionality of remote reference layer?
  • What is mapping mechanism used by java to identify IDL language?
  • What is middleware? What is functionality of web server?
  • What is polymorphism?
  • What is protocol used by server and client?
  • What is role of Web Server?
  • What is root class for all java classes?
  • What is serializable interface?
  • What is serialization?
  • What is thread?
  • What is update method called?
  • What is use of interface?
  • What is user defined exception?
  • When will you use interface and abstract class?
  • Where are card layouts used?
  • Why do we use oops concepts? What is its advantage?
  • Why do you canvas?
  • Why does java not support multiple inheritance?
  • Why is java not fully objective oriented?
  • Why is java not pure oops?
  • Why java is considered as platform independent?
  • Why there are some null interface in JAVA? What does it mean? Give some null interface in JAVA?
  • Write down how will you create Binary tree?
  • Write program for recursive traverse?
  • what is meant wrapper classes?

OOAD and UML Interview Questions

  1. Can method be overloaded based on different return type but same argument type?
  2. Describe some techniques for expressing business rules/constraints either in UML or via other means.
  3. Describe the use of UML stereotypes in one of your recent projects (you used stereotypes to express what?). Feel free to include small example.
  4. Describe useful application of an “extends” use case (in what situations would you use an “extends” use case instead of any of the other kind of use case relationships?)
  5. Differentiate Aggregation and containment?
  6. Differentiate between template class and class template.
  7. Differentiate between the message and method.
  8. Differentiate persistent & non-persistent objects?
  9. Differentiate the class representation of Booch, Rumbaugh and UML?
  10. Do you feel UML (or other types of) models have any value once the implementation code has been generated? Why?
  11. Explain the difference between composition and aggregation.
  12. Explain the difference between design model and an implementation model.
  13. Explain the different relationship notations in UML that you have used (e.g., generalization, association, and so on.)
  14. If familiar with it, describe how you used any one of the “gang of four” design patterns in recent model you produced.
  15. If familiar with it, describe the “design by contract” approach.
  16. If familiar with it, describe the concept of UML profile.
  17. In RUP business modeling, what is the difference between Business Actor and Business Worker?
  18. In the past, have you ever traced design and/or implementation artifacts back to the user requirements? If yes, how?
  19. Is object persistence expressed in the analysis model, the design model or both? Explain.
  20. Is there anything in RUP that you would change in order to improve the efficiency of the development process. Fit in an analysis or design model?
  21. List out some of the object-oriented methodologies
  22. Object Oriented: Essentials and History
  23. What do u meant by “SBI” of an object?
  24. What is dangling pointer?
  25. What is down casting?
  26. What is meant by “method-wars”?
  27. What is modifier?
  28. What is the difference between business use case and system use case?
  29. What is the difference between cohesion and coupling? Why are “strong cohesion” and “loose coupling” patterns generally recommended in OOAD?
  30. What is the format in which model can be saved inventor/tool neutral way?
  31. When does name clash occur?
  32. Whether unified method and unified modeling language are same or different?
  33. Which UML diagrams have you used? Explain when to use one or the other. Use Case Diagram, Class Diagram, Sequence Diagram, Activity Diagram
  34. Who were the three famous amigos and what was their contribution to the object community?
  35. Why generalization is very strong?
  36. Would you use sequence diagram or an activity diagram to model process flow that has lot of conditional flows and concurrent processing?
Source :

C Programming Interview Questions

  • Are expressions arr and *arr same for array of integers?
  • Are variables argc and argv are local to main?
  • Bitwise operator for checking whether particular bit is on or off?
  • Bitwise operator for putting on particular bit in number?
  • Bitwise operator for turning off particular bit in number?
  • Can Structure contain Pointer to itself?
  • Can there be at least some solution to determine number of arguments passed to variable argument list function?
  • Can we specify variable field width in scanf() format string? If possible how?
  • Can you dynamically allocate arrays in expanded memory?
  • Can you use function fprintf() to display output on screen?
  • Can you write function similar to printf()?
  • Describe about storage allocation and scope of global, extern, static, local and register variables?
  • Difference : Strings and Arrays?
  • Difference : Structure and Unions?
  • Difference : arrays and linked list?
  • Difference : enumeration and set of pre-processor # defines?
  • Difference : functions memmove() and memcpy()?
  • Difference : functions rand(), random(), srand() and randomize()?
  • Difference : main() in C and main() in C++?
  • Difference : pass by reference and pass by value?
  • Difference : strdup and strcpy?
  • Differentiate between for loop and while loop? it uses?
  • Does mentioning array name gives base address in all contexts?
  • Does there exist any other function that can be used to convert integer or float to string?
  • Does there exist any way to make command line arguments available to other functions without passing them as arguments to function?
  • Explain one method to process entire string as one unit?
  • How are Structure passing and returning implemented by complier?
  • How can called function determine number of arguments that have been passed to it?
  • How can we check whether contents of two structure variables are same or not?
  • How can we read/write Structures from/to data files?
  • How much maximum can you allocate in single call to malloc()?
  • How will you declare array of three function pointers where each function receives two ints and returns float?
  • If we want that any wildcard characters in command line arguments should be appropriately expanded, are we required to make any special provision? If yes, that?
  • In header file whether functions are declared or defined?
  • In header files whether functions are declared or defined?
  • Increase size of dynamically allocated array?
  • Increase size of statically allocated array?
  • Out of fgets() and gets() that function is safe to use and why?
  • Program : compare two strings without using strcmp() function.
  • Program : concatenate two strings.
  • Program : find Factorial of number.
  • Program : generate Fibonacci Series?
  • Program : interchange variables without using third one.
  • Program : s for String Reversal. same for Palindrome check.
  • Program : that employs Recursion?
  • Program : that uses command line arguments.
  • Program : that uses functions like strcmp(), strcpy(), etc.
  • To that numbering system can binary number be easily converted to?
  • Use bsearch() function to search name stored in array of pointers to string?
  • Use functions fseek(), freed(), fwrite() and ftell()?
  • Use functions memcpy(), memset(), memmove()?
  • Use functions randomize() and random()?
  • Use functions sin(), pow(), sqrt()?
  • Use qsort() function to sort array of structures?
  • Use qsort() function to sort name stored in array of pointers to string?
  • What advantages of using Unions?
  • What do functions atoi(), itoa() and gcvt() do?
  • What do ‘c’ and ‘v’ in argc and argv stand for?
  • What does error ‘Null Pointer Assignment’ mean and what causes this error?
  • What does static variable mean?
  • What is NULL Macro? Difference : NULL Pointer and NULL Macro?
  • What is NULL Pointer? Whether it is same as uninitialized pointer?
  • What is far pointer? where we use it?
  • What is linklist and why do we use it when we have arrays? - I feel correct answer should be linklist is used in cases where you don’t know memory required to store data structure and need to allocate is dynamically on demand.
  • What is maximum combined length of command line arguments including space between adjacent arguments?
  • What is near, far and huge pointers? How many bytes are occupied by them?
  • What is object file? How can you access object file?
  • What is pointer?
  • What is recursion?
  • What is similarity between Structure, Union and enumeration?
  • What is static identifier?
  • What is structure?
  • What is use of typedef?
  • When reallocating memory if any other pointers point into same piece of memory do you have to readjust these other pointers or do they get readjusted automatically?
  • Where are auto variables stored?
  • Where does global, static, local, register variables, free memory and C Program instructions get stored?
  • Write down equivalent pointer expression for referring same element a[i][j][k][l]?
  • advantages of using pointers in program?
  • advantages of using typedef in program?
  • bit fields? What is use of bit fields in Structure declaration?
  • declare following: array of three pointers to chars, array of three char pointers, pointer to array of three chars, pointer to function that receives int pointer and returns float pointer, pointer to function that receives nothing and returns nothing
  • detect loop in linked list?
  • differences between malloc() and calloc()?
  • differences between structures and arrays?
  • different storage classes in C?
  • dynamically allocate one-dimensional and two-dimensional array of integers?
  • enumerations?
  • implement substr() function that extracts sub string from given string?
  • macros? advantages and disadvantages?
  • obtain current time and Difference : two times?
  • obtain segment and offset addresses from far address of memory location?
  • print string on printer?
  • register variables? advantage of using register variables?
  • that function should be used to free memory allocated by calloc()?
  • that header file should you include if you are to develop function that can accept variable number of arguments?

Data Structure Interview Questions

  • A list is ordered from smaller to largest when sort is called. Which sort would take longest time to execute?
  • A list is ordered from smaller to largest when sort is called. Which sort would take shortest time to execute?
  • Convert following infix _expression to post fix notation ((a+2)*(b+4)) -1 (Similar types can be asked)
  • Evaluate following prefix _expression ” ++ + - (Similar types can be asked)
  • Explain about types of linked lists
  • Explain binary searching, Fibinocci search.
  • Explain quick sort and merge sort algorithms and derive time-constraint relation for these.
  • How is it possible to insert different type of elements in stack?
  • How many different binary trees and binary search trees can be made from three nodes that contain key values 2 & 3?
  • How will inorder, preorder and postorder traversals print elements of tree?
  • How would you sort linked list?
  • In which data structure, elements can be added or removed at either end, but not in middle?
  • Parenthesis are never needed in prefix or postfix expressions. Why?
  • Stack can be described as pointer. Explain.
  • The element being searched for is not found in array of elements. What is average number of comparisons needed in sequential search to determine that element is not there, if elements are completely unordered?
  • What data structure would you mostly likely see in non recursive implementation of recursive algorithm?
  • What do you mean by Base case, Recursive case, Binding Time, Run-Time Stack and Tail Recursion?
  • What do you mean by: * Syntax Error * Logical Error * Runtime Error How can you correct these errors?
  • What does abstract data type means?
  • What is average number of comparisons in sequential search?
  • What is average number of comparisons needed in sequential search to determine position of element in array of elements, if elements are ordered from largest to smallest?
  • What is data structure?
  • What is maximum total number of nodes in tree that has N levels? Note that root is level (zero)
  • When will you sort array of pointers to list elements, rather than sorting elements themselves?
  • Which data structure is needed to convert infix notations to post fix notations?
  • Which one is faster? binary search of orderd set of elements in array or sequential search of elements.
  • Which sort show best average behavior?
  • Write Binary Search program
  • Write programs for Bubble Sort, Quick sort
  • Write programs for Linked List (Insertion and Deletion) operations

A lot of Programming books

here tons of programming books. easy to download...................

Monday, February 11, 2008

Ajax.NET - A free library for the Microsoft .NET Framework

Ajax.NET - Download Details
Download the latest Ajax.dll ( to use it for free in your web projects.
You can also download the Ajax.dll ( Beta for the new Microsoft .NET Framework 2.0.
The source code of Ajax.NET is now available! More details...

UpdatePanel tutorial ASP.NET AJAX

What ist the UpdatePanel in ASP.NET Ajax? The answer is easy: When adding an UpdatePanel-control to your page, you can achieve a partial-update of your page on a postback. Only the content in the UpdatePanel is refreshed, the other parts of the page remain unchanged. This topic explains, how you can setup an Ajax-enabled project and use the UpdatePanel control.

A Chat with ASP.NET and Ajax

This article describes how to implement a web-chat with ASP.NET and Ajax. In the first part I introduce the technologies I used for the application. Then I explain the concept of a chat and in the last part I present the main implementations.The goal of this article is to show the interested reader how to develop a chat without browser-plugins or java-applets, just pure HTML and javascript.

CakePHP News

The CakePHP Development Site

Submitting Tickets
Before submitting a ticket read this: Bug Reporting. Make sure you have searched the CakePHP Google Group, and through the tickets that have already been submitted. Another suggestion is to grab the latest nightly or use the branch where many problems are fixed on a daily basis. You must be registered to submit tickets: Register here.

Latest Version


1.1 Nightly Build
svn co /path/to/save
Whats in 1.2?
CakePHP pre-beta
1.2 Nightly Build
svn co /path/to/save

Documentation Efforts
We are still hard at work on the documenation. You can help by submitting Documentation tickets. The Documentation tickets could be bugs (if you find a typo or problem), enhancements (if you know a cool function and want to document it) or RFCs ( if you want something described better). Hopefully, this will help centralize the efforts in our ongoing attack to get all the features documented. Select the milestone/version for 1.x.x.x Manual and we will do our best to have updates quickly.
Getting Started with Cake
The Bakery
CakePHP Manual
CakePHP Google Group
Visit us at #cakephp on
* Remember that when you submit something to this site, you are giving us permission to use, reproduce, and modify the contribution in any way, shape, or form.
addHeadingLinks(document.getElementById("searchable"), "Link to this section");

Sending emails

PHP offers the possibility to send email in a simple easy way, to that end the language provides us with the statement mail()
More details:

Method GET y POST

In the previous page we have indicated that data in a form is sent through the method indicated in the attribute METHOD of the tag FORM, the two possible methods are GET and POST.

The difference between these two methods is in the way of sending data to the page, while the GET method sends data using URL, the POST method sends them through the standard entrance STDIO

more details:

Thursday, February 7, 2008

CakePHP Links
The official website

The Manual
The Cake manual

The entire Cake API document

The Google Group
Actively discussing Cake development

Blogs about Cake
gwoo's blog about Cake, written in Cake

Cake baker
Daniel Hofstetter's blog about using Cake

Fabio Cevasco's site written in Cake

Ajax Professional Programmer

Where are you?
Ajax professional programmer?
I know where your are! ;-)
I think this a best and small ajax professional programmer choice:
Small. Compact. Useful. Ajax.
But if you ajax professional programmer, may be you wanna to use
More Object Oriented Library for real ajax professional programmer in ajax style.But as for me, not ajax (not so) professional programmer -
it's hard to understanding, and really better to use small and for dummies (like me) jQuery lib.Ok, resume: The Better Choice for Ajax Professional Programmer - jQuery. Yah Yah! ;-)))

Easy Way To Upload Files Up To Your Server

(You can find fresh version of this component at Code Snippet)
Just one moment! Do not use
$html->file ('UserFile');
Because construction
$_FILES['data[User][File]'] doesn't work (PHP 4.1.* at least).
So use standart html code:

Remember, You must creating directory at your webroot ;-)
With 777 access ;-) ..........................

How To Integrate WYSIWYG Editor into CakePHP?

Easy way to integrate Xihna into CakePHP.
Easy way to integrate TinyMCE into CakePHP.
And, of couse, it's SO EASY to integrate FCKEditor into CakePHP ;-)
But if you asked me about WYSIWYG Editor, I say to you: "I don't like WYSIWYG! And use MarkDown PHP.
So, about MarkDown "non-visual editor" next time. Ok? ;)

Need Different Title For Page? It's simple!

Just add this code in head your views:

pageTitle="Page title goes here"?>

But remember, in cakephp 1.2.xx you can achieve this by
$this->set(‘title’, ‘Foo bar’);
Of couse, you must setup this variable (pageTitle) in your controller ;-)

Navigation Helper The Best of!

If you want get code like this:

You can use useful ;) helper - Navigation Helper!
Code like this:
link('My account',"/users/account/",array('activeAction'=>'account'))?>
link('Create Item',"/items/add/",array('activeAction'=>'add','activeController'=>'items'))?>
link('Create Item',"/users/add/",array('activeAction'=>'add','activeController'=>'users'))?>
So... When user travel into your site and change /items/add -> users/add - the different menu be displayed (class = "active" I mean).
Just add code like thisrender(null,array('id'=>'main_nav'))?>
In your views! ;-)
Easy Way? Yes! Easy!
You can find more detail information here. And download navigation helper (sorry it's not direct link, because this file present in other blog).

How To Make Controller Without a Model?

class MyController extends AppController{
// var $uses = null; works too
var $uses = array();
function index() {
If you omit the “var $uses = array();” you will get a “missing model” error.
Thank's to CakeBaker!

How To Make Model Without a Table? Easy Decision!

The answer is simple:
class ModelWithoutTable extends AppModel {
var $useTable = false;

How To Validate data Without Saving?

You know, CakePHP check data only when you saving:
$this -> User -> save ($this->data)
But if you do not needing to save data?
In this case, you can use this "hint":
if ( $this -> User -> validates ( $this -> data ) ) { // OK, good to go
else { $this->set( 'data', $this->params['data'] ); $this->validateErrors( $this->User ); $this->render();
This code snippet made by Devo.

21 Things You Must Know About CakePHP

Easily creating static pages
I needed to create several pages that didn't use any models and contained static data inside the default layout. My first thought was to create a controller for these pages and define an action for each static page I needed. However, this solution seemed tedious and would make it difficult to quickly add new pages. Enter the pages controller - simply create a view inside the views/pages/ folder and it'll automatically be rendered in /pages. For example, if I created /views/pages/matt.thtml it would be accessible via

Static pages - Adjusting the page title
If you're using the pages controller and you need to change the page title, add the following to your view:
pageTitle = 'Title of your page.'; ?>

Static pages - Adjusting other data sent to the layout
If you need to send data to the layout (such as a variable indicating what section to highlight on the nav bar), add this to your view:
_viewVars['somedata'] = array('some','data'); ?>
That array should then be accessible as $somedata inside your layout.

Creating a simple admin center
If you need to create an administrative back-end for your CakePHP site and would like all the actions with administrative capabilities to exist under a specific folder, open up config/core.php and uncomment: define('CAKE_ADMIN', 'admin');This will then make all actions that are prefixed with "admin_" to be accessible via: /admin/yourcontroller/youraction. For instance, if I created an action in my posts controller called "admin_add," I would access this via: there I could simply password the admin folder to prohibit unwanted users from adding posts.

Viewing the SQL queries that are running behind the scenes
You can easily see the SQL queries that CakePHP is running by adjusting the DEBUG constant in config/core.php. 0 is production, 1 is development, 2 is full debug with SQL, and 3 is full debug with SQL and dump of the current object. I typically have debug set at 2, which renders a table at the bottom of the page that contains SQL debug information. If rendering a table at the bottom of your site is constantly breaking your layout during development (especially if you're making AJAX calls and you're getting SQL inside your pages, not just the bottom), you can easily style this table to be hidden by adding this to your CSS:
#cakeSqlLog { display: none; }
This will allow you to view debug information in the HTML source code without your layout getting mangled, just don't forget to set debug back to 0 when your site goes live.

Multiple sources of documentation
Don't just rely on the manual. The wiki and the API are invaluable sources of information. The tutorials in the wiki are especially useful, and the API may be daunting at first, but you'll quickly find the information in there is crucial to building a site with CakePHP.

Using bake.php
Bake is a command line PHP script that will automagically generate a model, controller, and views based on the design of your database. I highly recommend using scaffolding to get a prototype going of a table that may change a lot in the beginning. If you're fairly certain the data is not subject to any drastic change, I recommend using bake instead. With bake all the files are generated and written to disk and you can make modifications from there. It saves a lot of time doing the repetitive tasks such as creating associations, views, and the basic CRUD controller operations. Using bake is really easy. Once you have a table(s) in your database created, change directories to the /cake/scripts/ folder and run:
php bake.php
If you choose to bake interactively it'll walk you through the steps required to create your model, controller, and views. Once everything has been baked I usually go through all the generated code and make custom modifications as needed.

Mind permissions when moving cake around
When I changed from the development server to the live server I tarred up my entire cake directory and scp'd it to the new server. Immediately I started having an issue where any time the debug level was set to 0 (production mode), data would not be returned for certain database calls. This was a bit of a catch 22 since I needed to view debug information to troubleshoot the problem. Someone in #cakephp kindly pointed out that permissions on the /app/tmp folder need to be writeable by apache. I changed the permissions to 777 and the issue went away.

Complex model validation
I needed to validate beyond just checking to make sure a field wasn't empty or it matched a regular expression. In particular, I needed a way to verify that the email address users registered with was unique. In the wiki I found this gem: this advanced validation tutorial, which covers some advanced methods of validation that were very useful.

Logging errors
$this->log('Something broke');
This will log your error to /tmp/logs/ (I initially made the mistake of thinking it would log it to the apache error log)
Creating a controller that uses other models
Suppose you have a controller that needs data from a bunch of different models, simply add this to the top of your controller:
class yourController extends AppController {
var $uses = array('Post','User');
This controller would then have access to both the Post and the User model.

Creating a model for a table that doesn't actually exist in the database
I needed a way to create a model and controller without actually having an associated table in the database. I particularly wanted to make use of the $validate array so I could easily validate my fields and keep the validation logic in the model. CakePHP will throw an error if you create a model for a table that doesn't exist. Adding this to the model fixed the problem:
var $useTable = false;
You can use this to change tables names as well.
var $useTable = 'some_table';

Call exit() after redirecting
This should be no surprise to anyone who has done any serious web development in the past, but make sure you call exit() after running $this->redirect() if there's code afterward that you don't want to run. I've always done this in the past, but I made the assumption that $this->redirect() would make an exit call for me (which it didn't).

Advanced model functions
Unless you delve in to the API, there are some very useful model functions at your disposal you might not know exist. I highly recommend reading over the Model Class Reference at least once. Here's a few key functions I wasn't aware of that I found to be very useful:
generateList() - I use this function primarily to populate select boxes with data from associated tables
findBySql() - Sometimes you just need to write your own SQL
findCount() - Returns number of rows matching given SQL condition
hasAny() - Returns true if a record that meets the given conditions exists.
Again, I highly recommend reading over the entire model class reference, you'll be surprised at what you learn.

Inserting multiple rows in succession
I had a situation where I needed to iterate through a list of items and insert new rows for each. I quickly discovered that if you insert an item and then immediately insert another, the item that is inserted next doesn't insert at all. Instead the previously inserted row was being updated. For example:
$items = array('Item 1','Item 2','Item 3');
foreach ($items as $item) {
$this->Post->save(array('Post' => array('title' => $item)));
This code will result in a single entry in the posts table: "item 3." CakePHP inserted "item 1", but then updates it to become "item 2," then "item 3" because $this->Post->id gets the value of the last inserted ID. Normally this functionality is very useful, but in this particular instance it was not. I found was to setting $this->Post->id = false after each insert solved the problem.

Inserting logic before or after controller functions
Suppose you needed an array of colors to be available to every view rendered by your controller but you don't want to have to define this data in every action. Using the beforeRender() callback will allow you to do this:
function beforeRender() {
This would make $colors accessible in every view rendered by that controller. beforeRender() is called after the controller logic and just before a view is rendered. There's also beforeFilter() and afterFilter(), which are called before and after every controller action. For more information, read up on callbacks in the models section of the manual.

Adding a WYSIWYG editor to CakePHP
I found this great tutorial on getting TinyMCE set up with CakePHP. Basically you just link the tiny_mce .js file to your page and then add a small bit of init code to every page that you want textareas to be converted into TinyMCE editors.

Writing your own SQL for HABTM relationships
I had an issue with trying to create a HABTM (has-and-belongs-to-many) relationship where I needed to specify my own SQL statement. According to the docs (at the time of this writing) you should set finderSql in your model, but according to the cakePHP source you should set finderQuery instead. It's just a foul-up in the docs, but I figured it'd be worth noting to save others from having to figure it out for themselves. Trac ticket here:
Sending email
I found two tutorials in the wiki: Sending email and Sending email with PHPMailerI highly recommend the latter of the two, sending emails with PHPMailer is more secure and there's less of a headache because you don't have to deal with constructing the mail headers yourself.

Customizing HTML generated by the Helper
I needed to change the default "You can get a full list of available tags in /cake/config/tags.ini.php.
I wouldn't recommend modifying that file, however, because you could lose your changes when you upgrade CakePHP.

Creating a custom 404 error page
If you need to change the page that users see when a document is not found, create:/app/views/errors/error404.thtml

Source: Original >>