Wednesday, November 14, 2012

Using CKEditor with Javascript

CKEditor is an online rich text editor that can be embedded inside web pages. It is a WYSIWYG (What You See Is What You Get) editor which means that the text edited in it looks as similar as possible to the results end users will see after the document gets published. It brings to the Web popular editing features found in desktop word processors such as Microsoft Word and OpenOffice.org Writer. – Source: CKEditor Documentation
Before knowing about the CKEditor (previously FCKEditor), I was wondering if there is a tool in web that makes the document customizable. That means I was searching for web tool with which I can make sentences Bold, Italic or Numbered and Bulleted, or I can change Font size, font family, text color, or insert links, photos and many more without using HTML tags. Finally I came up with CKEditor which solves my problem. CKEditor is very easy to use and have very beautiful and user friendly interface like MS office and Open office.  In this tutorial I am going through all steps required to install and configure the CKEditor and show you a working example with Javascript.

Thursday, October 4, 2012

Missionaries and Cannibals problem in AI

Introduction
Missionaries and   Cannibals problem     is very famous      in  Artificial  Intelligence because    it was the   subject of   the first paper     that approached       problem formulation   from an analytical viewpoint.     The problem   can be stated   as follow.   Three missionaries   and three cannibals are on one side of a river, along with a boat that can hold one or two people. Now we have   to find   a   way to   get everyone   to the   other side,   without ever   leaving a   group of missionaries in one place outnumbered by the cannibals in another side. The above problem can be solved   by a   graph search   method.   Here   I   represent the   problem as   a   set of   states and operators. States are snapshots of the world and operators are those which transform one state into another state. States can be mapped to nodes of a graph and operators are the edges of the graph.
Explanation
Missionaries and   Cannibals can be solved by using different search algorithms like Breadth first and   Depth first   search algorithm to   find the solution. The   node   of   the   graph   to   be   searched   is   represented   by  a   state   space.   Each   state space can be represent by

Wednesday, July 11, 2012

Depth First Search in C++ – Algorithm and Source Code

Basic Theory
Depth – first searches are performed by diving downward into a tree as quickly as possible. It does this by always generating a child node from the most recently expanded node, then generating that child’s children, and so on until a goal is found or some cutoff depth point d is reached. If a goal is not found when a leaf node is reached or at the cutoff point, the program backtracks to the most recently expanded node and generates another of its children. This process continues until a goal is found or failure occurs.
Algorithm
An algorithm for the depth – first search is the same as that for breadth first search except in the ordering of the nodes.

Breadth First Search in C++ – Algorithm and Source Code

Basic Theory
Breadth – first searches are performed by exploring all nodes at a given depth before proceeding to the next level. This means that all immediate children of nodes are explored before any of the children’s children are considered. It has obvious advantage of always finding a minimal path length solution when one exists. However, a great many nodes may need to be explored before a solution is found, especially if the tree is very full.
Algorithm
BFS uses a queue structure to hold all generate but still unexplored nodes. The order in which nodes are placed on the queue for removal and exploration determines the type of search. The BFS algorithm proceeds as follows.

Friday, July 6, 2012

Step by step procedures to setup Android application development on Eclipse.

Step 1: Download JDK
Here is the link to download the JDK DOWNLOAD. Note: download the JDK that matches with your operating system i.e. download x64 version of JDK if you have x64 bit operating system for better performance.
Step 2: Download Eclipse
Download and install Eclipse from its official site. You can download any flavor of Eclipse i.e. Helios, Indigo, Galileo, Juno etc. But I prefer Eclipse Indigo. Note: download the Eclipse that matches with your operating system version.
Step 3: Download and Install ADT Plugin

Wednesday, July 4, 2012

Backup MySQL database from phpMyAdmin

MySQL database can be easily backed up from phpMyAdmin. Here are few steps :
  • Open phpMyAdmin using URL: http://localhost/phpmyadmin  in the case of Locahost otherwise  open it from your hosting server.
  • Select the database to backup.
  • Click Export.

Tuesday, July 3, 2012

Bike race game in C++ and SDL – Free download source code and executable file.

The bike race game is another mini project in C++ and SDL. The project is entirely focused on implementation of SDL in C++. SDL is a 2D gaming graphics library and is best for the beginner.
Programmers:
  1. Sanjeev Karn
  2. Shekh Maquesood Alam
  3. Swatantra Kumar Karna
Institute of Engineering, Pulchowk Campus, 065 Electrical Engineering

The source code is available on GitHub.

Wednesday, June 27, 2012

Solution of eight queens problem in Prolog

Eight queens problem is a constraint satisfaction problem. The task is to place eight queens in the 64 available squares in such a way that no queen attacks each other. So the problem can be formulated with variables x1,x2,x3,x4,x5,x6,x7,x8 and y1,y2,y3,y4,y5,y6, y7,y8; the xs represent the rows and ys the column. Now a solution for this problem is to assign values for x and for y such that the constraint is satisfied.
The problem can be formulated as
P={(x1,y1),(x2,y2),……………………..(x8,y8)} 
where (x1,y1) gives the position of the first queen and so on. So it can be clearly seen that the domains for xi and yi are  
Dx = {1,2,3,4,5,6,7,8}and Dy ={1,2,3,4,5,6,7,8} respectively. 
The constraints are
i. No two queens should be in the same row,
   i.e yi≠yj for i=1 to 8;j=1 to 8;i≠j
ii. No two queens should be in the same column,
  i.e xi≠xj for i=1 to 8;j=1 to 8;i≠j
iii. There should not be two queens placed on the same   diagonal line
  i.e (yi-yj) ≠ ±(xi-xj).
Now a solution to this problem is an instance of P wherein the above mentioned constraints are satisfied.

Friday, June 22, 2012

Simulation of Non-deterministic finite state automata using backtracking feature of prolog.

Let us now see how the features of prolog can be used to simulate a non-deterministic automata which would have been a cumbersome task using other programming languages.
A nondeterministic finite automaton is an abstract machine that reads a string of symbols as input and decides whether to accept or to reject the input string. An automaton has a number of states and it is always in one of the states. The automata can change from one state to another upon encountering some input symbols. In a non deterministic automata the transitions can be non deterministic meaning that the transition may take place with a NULL character or the same character may result in different transitions
A non deterministic automaton decides which of the possible moves to execute, and it chooses a move that leads to the acceptance of the string if such a move is available.
Let us simulate the given automata.

Thursday, June 21, 2012

Visual Prolog Program to delete a given element from the list.

To delete a element from a list the position and the element list is passed to the predicate delete. Then the delete predicate continuously breaks the list into head (H) and Tail (T) to find that the correct position is reached. On reaching the appropriate position to delete the element the predicate slices the head off the list and finally merges the remaining art with the rest. The prolog code is given as below:

DOMAINS
int_list = integer*

PREDICATES
del(integer, int_list, int_list)

CLAUSES
del(0,[H|T], T).
del(P,[H|T], [H|Z]):-
P1 = P - 1, del(P1,T,Z).

GOAL
del(2, [0,1,2,3,4,5],X).

Visual Prolog Program to append two list.

Here the two list are taken by the predicate “append” and returns the appended list. To append two list a list is broken continuously until the last empty list is encountered and finally the other list is appended or joined at the end of first recursively. The code to append is given as follows:

DOMAiNS
int_list = integer*

PREDICATES
append(int_list, int_list, int_list)

CLAUSES
append([],L,L).
append([H|L1], L2, [H|L3]):-append(L1,L2,L3).

GOAL
append([1,2,3,4],[5,6,7,8],Z).

Visual Prolog Program to find length of a list.

In this program the predicate length takes integer list and output a integer which is the length of list. Here the predicate length is called repeatedly or recursively until a last empty list is encountered and the 0 value is returned which is then continuously incremented to find the length.

Source Code

DOMAINS
int_list = integer*

PREDICATES
length(int_list, integer)

CLAUSES
length([],0).
length([H|T],L):-length(T,L1), L=L1+1.

GOAL
length([1,2,3,4,5],Z).

Visual Prolog Program to add the contents of an integer list.

Here in this program, the sum function is made that adds the contents of list. The first segment ( i.e the Domains section ) defines or declares the space dynamically for integer list. Then the predicate sum is defined that takes integer list and a Integer as arguments. The next clause section provides the necessary reasoning and facts to find the solution to the problem. Here the predicate sum is called recursively until it gets the last element of the list which is the empty list itself and returns 0 if empty list is encountered. The add predicate else adds the first element to the solution repeatedly to find the solution.

Source Code

DOMAINS
int_list = integer*

PREDICATES
sum(int_list, integer)

CLAUSES
sum([],0).
sum([H|T], X):-
sum(T,Y), X=H+Y.

GOAL
sum([1,8],Z).

List Manipulation in Prolog

List is one of the most important data structure in Prolog. Lists are contained in square brackets with the element being separated by commas. Here’s is an example.

[Nepal, India, Bhutan, Sri Lanka, Maldives, Pakistan, Bangladesh]

This is the list of seven atoms Nepal, India, Bhutan, Sri Lanka, Maldives, Pakistan, Bangladesh. Element of lists could be any valid Prolog terms, i.e. atoms, numbers, variables or compound terms. This includes other lists too. The empty list is written as []. The following is another example of list.

[Mango, X, [], son (Dasarath, X), [x, y, z], func(5)]

Head and Tail in List

The first element of a list is called its head and the remaining list is called the tail. An empty list doesn’t have a head. A list just containing a single element has a head (namely that particular single element) and its tail is the empty list. In above example of lists of countries in SAARC, Nepal is head and remaining countries constitute tail and this is represented as

[Nepal | [India, Bhutan, Sri Lanka, Maldives, Pakistan, Bangladesh]]

A list containing exactly one element has one head and empty tail. We will see some operations on List in Next Tutorial.

Prolog program to find Factorial of an Integer

PREDICATES
factorial(integer, integer)

CLAUSES
factorial(0,1).
factorial(X,Y):-
X<>0, S=X-1, factorial(S,Y1), Y=X*Y1.

GOAL
write("The value of Z is "),
factorial(5,Z).

Friday, May 11, 2012

Font rendering in GLUT using bitmap fonts with Sample example.

GLUT supports two type of font rendering: stroke fonts, meaning each character is rendered as a set of line segments; and bitmap fonts, where each character is a bitmap generated with glBitmap. Stroke fonts have the advantage that because they are geometry, they can be arbitrarily scale and rendered. Bitmap fonts are less flexible since they are rendered as bitmaps but are usually faster than stroke fonts. In this tutorial I will explain about Bitmap fonts. The function that renders bitmap character using OpenGL is glutBitmapCharacter. The syntax is

glutBitmapCharacter (void *font, int character);

font –> bitmap font to use and character –> Character to render.
For example,
glutBitmapCharacter(GLUT_HELVETICA_10,'a');
outputs a single character ‘a’ at the current raster position.
There are 7 bitmap fonts available in GLUT. They are
  • GLUT_BITMAP_8_BY_13
  • GLUT_BITMAP_9_BY_15
  • GLUT_BITMAP_TIMES_ROMAN_10
  • GLUT_BITMAP_TIMES_ROMAN_24
  • GLUT_BITMAP_HELVETICA_10
  • GLUT_BITMAP_HELVETICA_12
  • GLUT_BITMAP_HELVETICA_18
You can render the character in any raster position of the window. The raster position can be set using family of functions glRasterPos from OpenGL library. The syntax of the functions are:

void glRasterPos2f(float x, float y);
void glRasterPos3f(float x, float y, float z);

GLUT Tutorial - Creating Menus and Submenus in GLUT

GLUT supports simple cascading pop-up menus. They are designed to let a user select various modes within a program. The functionality is simple and minimalistic and is meant to be that way. Do not mistake GLUT’s pop-up menu facility with an attempt to create a full-featured user interface. glutCreateMenu creates a Menu in GLUT. The syntax of glutCreateMenu is

int glutCreateMenu(void (*func)(int value));

This function defines the callback that has to be called when a menu item was selected. This callback function has one parameter, the value. This function returns an int, this is the menu identifier. This identifier is needed when you would want to attach this menu as a submenu. This is illustrated in sample example later.

Thursday, May 10, 2012

Rendering Teapot glutSolidTeapot and glutWireTeapot using GLUT in C

GLUT provides function glutSolidTeapot to render a Solid Torus and glutWireTeapot to render a Wire Frame Torus. glutSolidTeapot and glutWireTeapot render a solid or wireframe teapot respectively. Both surface normals and texture coordinates for the teapot are generated. The teapot is generated with OpenGL evaluators. Here are the syntax of both the above functions

void glutSolidTeapot (GLdouble size);
void glutWireTeapot(GLdouble size);

Where, size –> Relative size of Teapot

Rendering Dodecahedron, Octahedron, Tetrahedron and Icosahedrons using GLUT in C

GLUT provides functions with no parameters and pre – assigned radii for these Objects. The pre – assigned radii of Dodecahedron, Octahedron, Tetrahedron and Icosahedrons are, respectively, sqrt(3), 1, sqrt(3), 1.  The syntax of each object is given below

Dodecahedron
void glutSolidDodecahedron (void);
void glutWireDodecahedron (void);
Octahedron
void glutSolidOctahedron (void);
void glutWireOctahedron (void);
Tetrahedron
void glutSolidTetrahedron (void);
void glutWireTetrahedron (void);
Icosahedrons
void glutSolidIcosahedron (void);
void glutWireIcosahedron (void);

Rendering Torus glutSolidTorus and glutWireTorus using GLUT in C

GLUT provides function glutSolidTorus to render a Solid Torus and glutWireTorus to render a Wire Frame Torus. glutSolidTorus and glutWireTorus render a solid or wireframe torus (doughnut) respectively centered at the modeling coordinates origin whose axis is aligned with the Z axis. Here are the syntax of both the above functions

void glutSolidTorus (GLdouble innerRadius, GLdouble outerRadius, GLint nsides, GLint rings);
void glutWireTorus (GLdouble innerRadius, GLdouble outerRadius, GLint nsides, GLint rings);

Where, innerRadius –> Inner Radius of the Torus, outerRadius –> Outer Radius of the Torus,  nsides –> Number of sides for each radial section, rings –> Number of radial divisions for torus.

Wednesday, May 9, 2012

Rendering Cones glutSolidCone and glutWireCone using GLUT in C

GLUT provides function glutSolidCone to render a Solid Cone and glutWireCone to render a Wire Frame Cone. glutSolidCone and glutWireCone render a solid or wireframe cone respectively oriented along the Z axis. The base of the cone is placed at Z = 0, and the top at Z = height. The cone is subdivided around the Z
axis into slices, and along the Z axis into stacks. Here are the syntax of both the above functions

void glutSolidCone (GLdouble base, GLdouble height, GLint slices, GLint stacks);
void glutWireCone (GLdouble base, GLdoube height, GLint slices, GLint stacks);

Where, base –> The radius of base of the  cone, height –> height of the cone,  slices –> The number of subdivision around the Z-axis and stacks –> The number of subdivisions along the Z-axis.

Tuesday, May 8, 2012

Rendering Spheres glutSolidSphere and glutWireSphere using GLUT in C – A sample program

GLUT provides function glutSolidSphere to render a Solid Sphere and glutWireSphere to render a Wire Frame Sphere. They Render the spheres centered at the modeling coordinates origin of the specified radii. The sphere is subdivided around the Z axis into slices and along the Z axis into stacks. Here are the syntax of both the above functions

void glutSolidSphere (GLdouble radius, GLint slices, GLint stacks);
void glutWireSphere (GLdouble radius, GLint slices, GLint stacks);

Where, radius –> The radius of the spheres, slices –> The number of subdivision around the Z-axis and stacks –> The number of subdivisions along the Z-axis.

Monday, May 7, 2012

PHP with MySQL: How to connect to MySQL database using PHP?

Connection to MySQL database using PHP is very simple and includes only few steps. First of all we establish a connection to database using username and password. Then we select the database that is already created using MySQL console or PhpMyAdmin. Then some operations are performed on data and finally we close the connection.
For the connection to MySQL, we need a database. So lets create a database with name testDB having one table user with three fields id, username and password  using MySQL console. Enter the following command in MySQL console and hit Enter. (MySQL console is generally located in C:\wamp\bin\mysql\mysql5.1.36\bin in WAMP server, the mysql version may be different in your case)
mysql> CREATE DATABASE testDB;
It creates a database with name testDB. In order to perform the operations on a database we must use the database. So to use the database testDB, insert the following command and hit enter.
mysql> USE testDB;
Now we create a table with fields id, username and password.

Monday, April 23, 2012

Troubleshooting MySQL error #1045 using WAMP

This tutorial will clarify with necessary illustrations and figures how to avoid #1045 error using WAMP server. For other servers like LAMP, this tutorial may not be helpful. When you install WAMP and try to connect MySQL server using phpMyAdmin for the first time then MySQL refuses the connection displaying #1045 error. It is look like the figure below
MySQL Error 1045
Procedure to Troubleshoot

Top Collections(Lists) of Mini Projects in C and C++ free download source code and exe.

Here are the collections of Mini Projects in c and c++ with full source code and executable file. All the codes are compiled using GCC Compiler in Code::Blocks IDE in Windows platform. So the code may produce errors if compiled on other platforms and compilers. All the visitors are requested to use these projects as a reference purpose only. Submitting these projects as college/school mini project without modification or only little modification is completely discouraged. They are created to help you to develop ideas about the mini project, topics, writing styles, file handling etc. Analyze these projects and obtain the ideas and try to write the code yourself.

Wednesday, April 4, 2012

Computer Graphics (cg) mini project illumination model free download

To download the project click here .
This project is based on various algorithms used in computer graphics. Illumination is the key feature of the project. It draws two shapes namely diamond and cone. The two objects are rotated about various directions. Light source can be set by using mouse position. The area inside the window where you click becomes the light source. The project uses vertex table, edge table and surface table to store the geometric information about the object. The cone and diamond are made using small polygon and each polygon is illuminated with different light illumination calculated by using vectors. The source code is written in C# in Visual Studio 2010.

Saturday, March 31, 2012

3D Rotation Algorithm about arbitrary axis with C/C++ code

When an object is to be rotated about an axis that is not parallel to one of the coordinate axes, we need to perform some additional transformations. In this case, we also need rotations to align the axis with a selected coordinate axis and to bring the axis back to its original orientation. Given the specifications for the rotation axis and the rotation angle, we can accomplish the required rotation in five steps.
  1. Translate the object so that the rotation axis passes through the coordinate origin.
  2. Rotate the object so that the axis of rotation coincides with one of the coordinate axes.
  3. Perform the specified rotation about that coordinate axis.
  4. Apply inverse rotations to bring the rotation axis back to its original orientation.
  5. Apply the inverse translation to bring the rotation axis back to its original position.

Cohen-Sutherland Line Clipping Algorithm with C/C++

Theory
In this method, every line endpoint is assigned a four digit binary code(region code) that identifies the location of the point relative to the boundary.
b1 : left 
b2 : right 
b3 : below 
b4 : above
The value 1 indicates its relative position. If a point is within clipping rectangle then region code is 0000. So , 
If x – xwmin < 0 , b1 = 1 
If xwmax – x < 0 , b2 = 1
If y – ywmin < 0 , b3 = 1 
If ywmin – y < 0 , b4 = 1 
If the region codes of both end points are 0000 then we accept
the line.  Any  line that have one in the same bit position is rejected  i.e  If RA AND RB ≠ 0 ,line is completely outside . 
The lines which con not be identified as completely inside or outside a window by these tests are checked for intersection with the window boundary. Such lines may or may not cross into the window interior.

Liang-Barsky Line Clipping Algorithm with C/C++

Theory
In Liang-Barsky algorithm, we first write the point-clipping conditions in parametric form as 
Parametric Form
Each of these for inequalities can be expressed as inequalities , k = 1, 2, 3, …..
where parameter p and q are defined as
Boundaryparameter
Any line that is parallel to one of the clipping boundaries has pk = 0 for the value of k corresponding to that boundary. If, for that value of k, we also find qk < 0, then the line is completely outside the boundary and can be eliminated from further consideration. If qk >=0, the line is inside the parallel clipping boundary.
When pk <0, the infinite extension of the line proceeds from the outside to the inside of the inside of the infinite extension of this particular boundary. If pk > 0, the line proceeds from the insides to the outside. For a nonzero value of pk, we can calculate the value of u that corresponds to the point where the infinitely extended line intersects the extension of boundary k as u = qk / pk.

How to make Vertex Table, Edge Table and Surface Table to store geometric information of an object??

Listing the geometric data in three tables provides a convenient reference to the individual components of each object. Also, the object can be displayed efficiently be using data from the edge table to draw the component lines. Here I discuss about how to create those tables with the help of C++ code.
Vertex table consists of the array of vertices with the coordinate value of each vertex. In C++, a vertex table can be created by creating a class that has . For example
class vertex
{
    private:
    Point3D *points;
    public:
    vertex()
    {
        points = new Point3D();
    }
};

Wednesday, March 28, 2012

Numerical Methods: Multiplication of two matrices using two dimensional array in C

Let we have two 2 x 2 matrices A and B
\[ A = \begin{bmatrix} a_{00} & a_{01}\\
a_{10} & a_{11}
\end{bmatrix} \text{ and } B = \begin{bmatrix} b_{00} & b_{01} \\
b_{10} & b_{11} \end{bmatrix}\]
The multiplication of $A$ and $B$ works as follows

  1. Multiply $a_{00}$ with $b_{00}$ and $a_{01}$ with $b_{10}$ and sum them together. So the first element $r_{00}$ becomes  $a_{00}$ . $b_{00}$ $a_{01}$ . $b_{10}$
  2. Multiply $a_{00}$ with $b_{01}$ and $a_{01}$ with $b_{11}$ and sum them together. So the first element $r_{01}$ becomes  $a_{00}$ . $b_{01}$ $a_{01}$ . $b_{11}$
  3. Multiply $a_{10}$ with $b_{00}$ and $a_{11}$ with $b_{10}$ and sum them together. So the first element $r_{10}$ becomes  $a_{10}$ . $b_{00}$ $a_{11}$ . $b_{10}$
  4. Multiply $a_{10}$ with $b_{01}$ and $a_{11}$ with $b_{11}$ and sum them together. So the first element $r_{11}$ becomes  $a_{10}$ . $b_{01}$ $a_{11}$ . $b_{11}$
So the resulting matrix $R$ becomes, 
\[ R = \begin{bmatrix} a_{00}.b_{00}+a_{01}.b_{10} &  a_{00}.b_{01} + a_{01}.b_{11} \\ a_{10}.b_{00} + a_{11}.b_{10} & a_{10}.b_{01} + a_{11}.b_{11}\end{bmatrix}\]
Note: In order to multiply two matrices, $A$ and $B$, the number of columns in $A$ must equal the number of rows in $B$. Thus, if $A$ is an $m * n$ matrix and $B$ is an $r * s$ matrix, $n = r$.
Source Code
#include<stdio.h>
int main()
{
    int r1, c1, r2, c2, matrix1[10][10], matrix2[10][10], result[10][10];
    int i, j, k;
    printf("Enter the row and column of the first matrix: ");
    scanf("%d%d",&r1,&c1);
    printf("Enter the row and column of the second matrix: ");
    scanf("%d%d",&r2,&c2);
    if(c1 != r2){
        printf("Matrix multiplication impossible");
    }
    printf("Enter the first matrix: \n");
    for(i = 0; i <r1; i++)
       for(j = 0; j < c1; j++)
            scanf("%d", &matrix1[i][j]);
    printf("Enter the second matrix: \n");
    for(i = 0; i <r2; i++)
       for(j = 0; j < c2; j++)
            scanf("%d", &matrix2[i][j]);
    for(i = 0; i < r1; i++ ){
        for(j = 0; j < c2; j++){
            result[i][j] = 0;
            for(k = 0; k < c1; k++){
                result[i][j] += matrix1[i][k] * matrix2[k][j];
            }
        }
    }
    printf("The multiplication of the matrix is: \n");
    for(i = 0; i < r1; i++){
        for(j = 0; j < c2; j++){
            printf("%d", result[i][j]);
            printf(" ");
        }
        printf("\n");
    }
    return 0;
}

Friday, March 23, 2012

3D Transformation [Translation, Rotation and Scaling] in C/C++

Translation
In a three-dimensional homogeneous coordinates representation, a point is translated from position P = (x, y, z) to position P’ = (x’, y’, z’) with the following equations.
x’ = x + tx
y’ = y + ty
z’ = z + tz
Rotation about axes
To generate a rotation transformation for an object, we must designate an axis of rotation (about which the the object is to be rotated) and the amount of angular rotation. Unlike 2D applications, where all transformations are carried out in the xy plane, a three-dimensional rotation can be specified around any line in space. I will cover rotation about arbitrary axis in another post, here the discussion is restricted to rotation about coordinate axes.
About x – axis

Sunday, March 11, 2012

Computer Graphics: Fractals generation using Mandelbrot Set with C/C++ in Code::Blocks



"Clouds are not spheres, mountains are not cones, coastlines are not circles, and bark is not smooth, nor does lightning travel in a straight line." – Benoit Mandelbrot
The Mandelbrot set is created by a general technique where a function of the form
zn+1 = f(zn)
is used to create a series of a complex variable. In the case of the Mandelbrot, the function is
f(zn) = zn2 + zo
This series is generated for every initial point zo on some partition of the complex plane separating the complex plane into two categories:
  1. Points inside the Mandelbrot set
  2. Points outside the Mandelbrot set

Friday, March 9, 2012

Bezier Curves and Bezier Surfaces generation with C/C++ in Code::Blocks

Brief Theory of Bezier Curve
In order to draw curvy surface we implement Bezier curve algorithm. In drawing Bezier we first define n+1 control point pk = (xk, yk, zk) with k varying from 0 to n. And the coordinate points are blended to produce following position vectors that define the path of an approximation Bezier polynomial function between p0 and pn.
Beizer Polynomial Function
The Bezier blending functions BEZk,n(u) are the Bernstein polynomials:  BEZk,n(u)=C(n,k)uk(1-u)n-k
Where the C(n, k) are binomial coefficients.
Equivalently, we can define Bezier blending functions with the recursion calculation.
BEZk,n (u) = (1-u) BEZk,n-1(u)+u BEZk-1,n-1(u), n>k≥1
With BEZk,k = uk , and BEZ0,k = (1-u)k.


Sunday, March 4, 2012

Controlling Camera and Line of Sight in OpenGL

Camera controlling is essential in 3D viewing. OpenGL provides a function gluLookAt() for this purpose. The syntax of the function gluLookAt() is
void gluLookAt ( GLdouble eyex,
GLdouble eyey,
GLdouble eyez,
GLdouble centerx,
GLdouble centery,
GLdouble centerz,
GLdouble upx,
GLdouble upy,
GLdouble upz );



It takes three sets of arguments, which specify the location of the viewpoint, define a reference point toward which the camera is aimed, and indicate which direction is up. The first three numbers represent where the camera is positioned.

Friday, March 2, 2012

String To Integer and Integer to String Conversion in C

In modern languages like Java, C# etc., there is a provision of function to handle String to Integer and Integer to String conversion. But in case of C, you should explicitly convert.
String to Integer Conversion
String is a array of characters. So changing each character successively into integer  changes whole string into integer. To change a character into an integer, here is a simple idea. The idea is, subtract the zero character from the character you want to change. For example to change  character 1 into integer 1 subtract character 0 from character one i.e. ‘1’ - ‘0’ results integer 1. A portion of a C code is given below:

Tuesday, February 28, 2012

PHP Tutorial: Getting user input in PHP using HTML form

There are basically three ways in PHP to get user input. They are
  • Using HTML Form
  • Using URL values links
  • Using COOKIES
In this tutorial, I shall talk how to use HTML Form to get user input and retrieve that values from a web server. Form is simple HTML form start with <form> tag and end with </form>. The form is posted to the server using POST method and each data user has entered is stored in a PHP super global variable $\$\_POST$.  $\$\_POST$ is an associative array that stores variables in key => value format. Let us take an example of simple HTML form with two fields: username and password.

Monday, February 27, 2012

Fastest way of calculating Prime Number with less system overhead with C code.

A number is said to be a prime number if it is divisible only by 1 and  the number itself. That is prime number is divisible by exactly two numbers. For example, 11 is prime number because it is divisible by 1 and 11 itself  but 4 is not prime number because it is divisible by 1, 2 and 4.
Test of prime number is famous question in programming. You are supplied any arbitrary number and you have to find out whether it is prime or not. There are various methods and algorithms for testing the prime number condition. Some methods take less iteration and in turn less overhead and some  methods take large iteration and in turn large overhead. I will present you two methods; one uses large number of iterations and another uses drastically reduced number of iterations.
First method (High Iterations, Slow process)

Friday, February 24, 2012

Mini project Digital Volt Meter (DVM) using PIC16F877A with C code

DVM Project Overview
Digital Volt Meter is a Mini Project that I made as my project of the subject ‘Microprocessor Based Instrumentation System’. In this project I have used three major electronic components. They are PIC16F877A, LCD Display (16 X 2) and Low power Quad op-amp (LM324). PIC16F877A is used as an ADC module which converts the analog input into corresponding 10 bit digital output. It also provides enable and RS signals to the LCD display. LCD Display is used to display the converted digital binary data to decimal format so that user can easily understand the voltage. And finally Low power quad op-amp is used as buffer and as inverter. The DVM measures the voltages ranging from –50 V to +50 V

Wednesday, February 22, 2012

Configuring MonoDroid in Visual Studio 2010

In my previous article, I walked through the introduction of MonoDroid and the way to download the free version of MonoDroid installer. If you have downloaded the installer, then now I will show you how to download different components and install it and finally how to configure Mono for Android in Visual Studio 2010.
In first step double click the installer you have downloaded. A dialog box will appears that is all about welcoming you to installation process. Click Next button.

Saturday, February 11, 2012

Android App Development with MonoDroid using .NET framework in Visual Studio

The craze of smart phones is increasing day by day. Many people in the world use Smart Phones as they are portable, good looking, have high RAM and memory, high processor speed, good support for wireless and wifi and many more. iPhone, Android , Windows Phone 7 are some examples of smart phone. Among them android is most popular. It is because, it is open source, availability of large numbers of applications, large number of mobile company deploy it, large developer community and many more. So large number of mobile application developers are interested in Android Application Development. In this article, I focus on the Android App Development for C# .NET programmers using MonoDroid.
Android APP Development is mostly based on Java VM “Dalvik” with Eclipse IDE.

Friday, February 10, 2012

Different Data Types in PHP

PHP supports wide range of Data Types. It supports eight different primitive data types: four scalar types (boolean, integer, float, string), two command types: (array and object) and finally two special types (resource, NULL). All these data types are discussed below:
Boolean:
Boolean is data type whose value is either true or false. True and false in PHP are case insensitive. To specify a boolean literal, use the keywords TRUE or FALSE. For example:

PHP Tutorial: The Operational Trail

In this section, I discuss about the operation of server to process PHP code. TheOperationalTrail

When you request some file like http://yourdomain/test.php on a web browser, as shown in above figure, then following different operations are performed on server.

  • First web browser will make a request to the the server to find a page
  • The file is located on the hard drive of the server.
  • Because it has .php extension, it needs to process the PHP code which is done by the server.
  • If the file contains operations on database, then it sends/receives the data to/from database
  • At last server returns pure HTML code to the browser which browser can easily understand.

Thursday, February 9, 2012

Subtraction of two binary numbers using C

Basic Theory
Subtraction can be regarded as addition. For example A - B is same as A + (-B). In binary most computer uses 2’s complement form to represent negative binary number. The subtrahend is first converted to 2’s complement form to make it negative and then is added to minued. This is same as above example.
Code Assumption
This code is capable to perform subtraction between two decimal numbers from 0 to 127. The subtrahend is first converted into 2’s complement form and then addition is perform. After addition the result is obtained. If the result has 1 in its MSB then it is treated as negative result and is converted to decimal format otherwise it is treated as positive number and converted to positive decimal.
Source Code:

Addition of two binary numbers using C

Basic Theory
Addition of binary numbers is far simpler than that of decimal number. This is because, binary addition includes addition between 1 and 0 only. The addition process results into two unit: sum and carry
sum = a xor b xor c
carry = ab + bc+ ac
Initially the carry bit is set to be 0. This process is continue until all the bits in a binary number finish.

Code Assumption

The following code uses 8 – bit binary unsigned integer. This means each integer can hold from 0 to 255 in decimal. So user can add up to 255. If the result is greater than 255, then condition of overflow occurs. The code contains following segments
  • Decimal to Binary Conversion
  • Addition of two binary numbers
  • Binary to Decimal conversion

Wednesday, February 8, 2012

Getting Started with PHP : Writing Hello World Program

Lets start this section with small example, consider a small portion of PHP code

<?php
	$var = 5;
	echo "the value of variable is ". $var;
?>

This program simply outputs a string “the value of variable is 5” on a browser. Now lets see the mechanism how it works.


Every PHP code segment must start with <?php tag and end with ?> tag. Note that there is no space between < , ? and php. If web server finds <?php ?> tag on a web page that browser is requesting, then it converts all the PHP statement into corresponding HTML statement which browser can understand. If you run the above code on web server and view the source, then you see that there are no any php statements.


Every PHP variable declaration start with $ sign. PHP is not so strict like programming languages therefore all types of variable (int, float, string, long etc) can be declared by just writing $var_name. For example:

<?php
    $intvar = 5;
    $floatvar = 5.5;
    $stringvar = "nepal";
?>

To print a statement to a browser window, PHP command echo is used. The statement to be printed is kept inside single or double quotes. The . (dot) operator concatenates two string.


Embedding PHP code with HTML


PHP is designed to use with HTML. PHP alone cannot do anything. Any website needs different HTML tags. But PHP with HTML helps to create dynamic pages. So PHP code can be embedded inside HTML code as below.

<HTML>
<HEAD>
<TITLE>My First Program</TITLE>
<HEAD>
<BODY>
<?php
    $var = 5;
    echo "the value of variable is " . $var;
?>
</BODY>
</HTML>

Tuesday, February 7, 2012

Installing PHP using WAMP on windows

I gave you brief introduction of Wamp Server in my previous article and link to download it. Now I am going to write how Wamp server can be used to run the PHP code on windows. Wamp basically contains three components : Apache, PHP and MySQL. Besides  it contains quick links for Localhost and PhpMyAdmin.  You can edit php.ini file as well as other many files using wamp server. It also has MySQL Console window (command prompt). WAMP server configures all the components for you so that you don’t need to configure each component manually.  Now lets install the wamp server first

Installation:

http://www.wampserver.com is official site for wamp server. Browse the site and download the wamp server. After downloading , just double click the executable file WampServer2.0i.exe (or any other version) and install it.

Wamp Server

At the end of the installation , tick the check box start wampserver now . After you start wampserverm you will see a small icon  on the lower – right corner of desktop window. Click on the icon, a list of different files and folders like localhost, phpmyadmin, Apache, MySQLand PHP  pops up. Through this icon, you can put server online or offline, restart the services, edit the settings for PHP, see the versions of PHP , MySQL and Apache, jump to different directories and many more.

Testing the wampserver by running a sample php code.

Now wampserver is ready to use. Lets check  whether it is actually working or not. Open any web browser and type http://localhost or http://127.0.0.1 in URL Address bar. If wampserver is running, then a webpage is displayed (as shown in below) for you otherwise browser cannot find localhost.

Localhost

Open C drive then you will see a folder named wamp. Inside wamp there is a folder called www. This is the folder where each PHP file must be kept in order to run them. If you place PHP files other than inside www, then the browser cannot find your files. Make a text file and rename the name of the file as test.php. Inside test.php write following code. 

<HTML>
<HEAD>
<TITLE> Testing Wampserver </TITLE>
</HEAD>
<BODY>
<?php
    echo "Hello world";
?>
</BODY>
</HTML>

Save this file and type http://localhost/test.php one URL of the browser. Then you will see a webpage with Hello world written. This confirms that the server is working well on your computer  and you are ready to write a php code and run it.

Monday, February 6, 2012

Installation of PHP on Windows Platform

To run PHP code and see the output on Browser, you need following things

  1. A Web Server [e.g. Apache]
  2. PHP
  3. Database [e.g. MySQL]
  4. Text Editor [e.g. Notepad++, KOMODO, Text Mate]
  5. Web Browser [e.g. IE, Firefox, Google Chrome]

You can use any combination of them. Most people uses Apache as Web Server, PHP and MySQL as Database regardless of their platform.

PHP need 32 or 64 bit platform to work properly. PHP will not work on 16 bit platforms such as Windows 3.1.  Windows 98/Me/NT4 is no longer supported as of PHP 5.3.0. Windows 95 is no longer supported as of PHP 4.3.0.

There are two ways to install PHP on windows. One way of installing is to download each component (Apache, PHP and MySQL) separately and configure manually. Configuring PHP manually, which I think, is very cumbersome. You should follow a lot of steps very carefully. If you prefer to configure each component manually then here is the links to download

  1. Apache: httpd.apache.org

The other way of installing is to download a single pack which contains all these things (Apache, PHP and MySQL) . For windows, there are some single pack installer available on the internet.

  1. WAMP (Windows Apache MySQL PHP) : http://www.wampserver.com/en/index.php

Both are very handy and easy to use. But I will be using WAMP throughout my tutorial series. In next tutorial I will show you how to use WAMP on windows.

Sunday, February 5, 2012

Why should we use PHP?

PHP is important tool for web development because of the following facts

  • PHP is open source and free software – You can use PHP without any cost.
  • PHP is cross platform to develop, to deploy and to use.
  • PHP is Powerful, Robust and Scalable.
  • PHP is web development specific.
  • PHP can be object oriented , especially version 5 or more.
  • PHP has Great Documentation in many languages.
  • PHP has large active developer community (more than 25 million websites)

What is PHP?

PHP, which stands for "PHP: Hypertext Preprocessor" is a widely-used Open Source general purpose scripting language that is especially suited for Web development and can be embedded into HTML. Here are some points that define PHP.

  • PHP is a scripting language but not programming language.
  • PHP is server – side scripting language. PHP code is only recognized by web servers. Web Browsers do not recognize PHP and can’t response it.
  • PHP need a web server in order to run its code. It does not need to be compiled like C, C++ or JAVA.
  • PHP is especially designed to use  with HTML. HTML alone can not provides flexibility to a website. PHP helps to create dynamic pages.
  • PHP syntax is very similar to that of C and Perl. Object oriented PHP syntax is similar to JAVA and C++.
  • The extension of PHP file must be .php. If you place PHP code in a file having extension .htm or .html then PHP code can not do anything.
  • PHP can be used on all major operating system like Microsoft Windows, Linux, Mac OS, RICS OS and others. So, with PHP, we are free to choose any kind of operating system you are familiar with.
  • PHP has support for must of the web server like Apache, IIS and many more.
  • With PHP you are not limited to output HTML. PHP's abilities includes outputting images, PDF files and even Flash movies (using libswf and Ming) generated on the fly. You can also output easily any text, such as XHTML and any other XML file. PHP can auto generated these files, and save them in the file system, instead of printing it out, forming a server-side cache for your dynamic content.
  • PHP has support for wide range of Databases.
  • PHP also has support for talking to other services using protocols such as LDAP, IMAP, SNMP, NNTP, POP3, HTTP, COM (on Windows) and countless others.
     
     
 

 

 

     

Saturday, February 4, 2012

Lightning in OpenGL with spot Light

So far we have seen lighting effects which have the following properties:

  • The light is being projected from an infinite distance.
  • The rate of fading of the brightness at the circumference is very low.

But, we might want to produce lights, which have a position in the scene and are not projected from an infinite source unlike the normal lighting which we have seen so far. Like a study lamp or a spot light on a pool table, etc.

Source Code:

#include <windows.h>
#include <GL/glut.h>
static double yVal=1.0;
int spot(double a, double b, double c, double d, double e, double f){
    /*
    a, b and c -- x, y and z co-ordinates for light position
    d, e and f -- x, y and z co-ordinates for spot light position
    */
    GLfloat mat_specular[] = { 0.3, 1.0, 0.3, 1.0 };
    GLfloat mat_shininess[] = { 50.0 };
    GLfloat light_position[] = { a,b,c, 1.0 };
    GLfloat spotDir[] = { d,e,f };
    glClearColor (0.5, 0.5, 0.5, 0.0);
    glShadeModel (GL_SMOOTH);
    glLightfv(GL_LIGHT0,GL_SPECULAR,mat_specular);
    glLightfv(GL_LIGHT0,GL_POSITION,light_position);
    glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
    glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
    // Definig spotlight attributes
    glLightf(GL_LIGHT0,GL_SPOT_CUTOFF,95.0);
    glLightf(GL_LIGHT0,GL_SPOT_EXPONENT,2.0);
    glLightfv(GL_LIGHT0,GL_SPOT_DIRECTION,spotDir);
    glEnable(GL_COLOR_MATERIAL);
    glEnable(GL_DEPTH_TEST);
    return 0;
}
void drawSphere(){
    GLUquadricObj* cyl;
    glClearColor (0.5, 0.5, 0.5, 0.0);
    GLfloat light_position[] = { 50.0, 50.0 , 0.0, 1.0 };
    GLfloat mat_specular[] = { 0.3, 0.3, 1.0, 1.0 };
    GLfloat mat_shininess[] = { 100.0 };
    GLfloat spotDir[] = { 50.0, 30.0, 0.0 };
    glShadeModel (GL_SMOOTH);
    spot( yVal,5.0,1.5,10.0,1.0,10.0);
    glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
    glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
    glMatrixMode (GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(35.0, 1.0, 1.0, 100.0);
    glMatrixMode (GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt (30.0, 0.0, 10.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0);
    cyl = gluNewQuadric();
    gluQuadricDrawStyle(cyl, GLU_FILL);
    glPushMatrix();
    gluSphere(cyl, 4.0, 1000, 1000);
    glPopMatrix();
    glFlush();
}
void display(void){
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    drawSphere();
    glFlush ();
}
void init (void){
    glClearColor (0.5, 0.5, 0.5, 0.0);
    glEnable(GL_DEPTH_TEST); //enabling z-buffer
    /* initialize viewing values */
    glMatrixMode (GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(35.0, 1.0, 1.0, 100.0);
    glMatrixMode (GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt (30.0, 0.0, 10.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
}
void keyboard(unsigned char key, int x, int y){
    switch (key) {
        case 27: // “esc” on keyboard
        exit(0);
        break;
        case 97: // “a” on keyboard
        yVal++;
        glutPostRedisplay();
        break;
    }
}
int main(int argc, char** argv){
    glutInit(&argc, argv);
    glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize (600, 600);
    glutInitWindowPosition (100, 100);
    glutCreateWindow ("Spot Light - Programming Techniques");
    init ();
    glutDisplayFunc(display);
    glutKeyboardFunc(keyboard);
    glutMainLoop();
    return 0;
}

Output


Spot Light in OpenGL

Lightning in OpenGL with Material Effect

This is second tutorial on Lightning in OpenGL. In this tutorial, I will discuss about producing Material Effect in OpenGL. Material parameters specify how a surface reflects light. Applications change OpenGL material parameters to emulate different colored materials, shiny and flat materials, high gloss materials such as pool ball, etc.
The routine glColor3f(), sets the primary color and is a good idea to call this routine as long as we are not using lighting effects. The OpenGL lighting doesn’t use the primary color, instead uses the material colors. Hence it is important to introduce materials while talking about lighting.

So far we have seen a simple lighting example which has no material effects. But, in order to make the scene more attractive, we have to make use of materials. In the following code, we have used a green material. We make use of GL_SPECULAR, GL_AMBIENT, GL_SHININESS depending on the
scene requirements. The same parameters are also applicable to lighting methods.

Source Code:

#include <windows.h>
#include <GL/glut.h>
static double yVal=50.0;
void drawSphere(){
    GLUquadricObj* cyl;
    GLfloat light_position[] = { 0.0, 40.0, yVal, 0.0 };
    glLightfv(GL_LIGHT0, GL_POSITION, light_position);
    GLfloat mat_specular[] = { 0.3f, 1.0f, 0.3f, 1.0f }; // Green color material
    GLfloat mat_shininess[] = { 70.0 }; // Defines shininess
    glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); // Using materials
    glMaterialfv(GL_FRONT, GL_AMBIENT, mat_specular);
    glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
    glMatrixMode (GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(35.0, 1.0, 1.0, 100.0);
    glMatrixMode (GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt (30.0, 0.0, 10.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0);
    cyl = gluNewQuadric();
    gluQuadricDrawStyle(cyl, GLU_FILL);
    gluSphere(cyl, 2.0, 50, 50);
    glFlush();
}
void display(void){
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    drawSphere();
    glFlush ();
}
void init (void){
    glClearColor (0.5, 0.5, 0.5, 0.0);
    glEnable(GL_DEPTH_TEST); //enabling z-buffer
    glMatrixMode (GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(35.0, 1.0, 1.0, 100.0);
    glMatrixMode (GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt (30.0, 0.0, 10.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
}
void keyboard(unsigned char key, int x, int y){
    switch (key) {
        case 27: // “esc” on keyboard
        exit(0);
        break;
        case 97: // “a” on keyboard
        yVal = yVal-5.0;
        glutPostRedisplay();
        break;
    }
}
int main(int argc, char** argv){
    glutInit(&argc, argv);
    glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize (600, 600);
    glutInitWindowPosition (100, 100);
    glutCreateWindow ("Light Material effect - Programming Techniques");
    init ();
    glutDisplayFunc(display);
    glutKeyboardFunc(keyboard);
    glutMainLoop();
    return 0;
}


Output


Lightning in OpenGL with Material