Saturday, September 29, 2007

Return random rows using Sql query

Return random rows using Sql query

SELECT TOP 5 * FROM album ORDER BY NEWID()

Reloading A Page in javascript

Reloading A Page in javascript

location.reload();
reloading by preventing caching:location.search = "?" + Math.random();

Redirecting a browser using javascript

Redirecting a browser using javascript


location.href = "newPage.html";

OR

<meta http-equiv="Refresh" content="X; URL=Y" />


OR

location.replace("newPage.html"); (This refreshes browser history)

prevent caching in javascript

prevent caching in javascript


document.write("<img src=\"yourimage.gif?" + Math.random() + "\" />");

Here Math.random() is the key here since its always different per load and enforces a different version!!.

Math.random() returns a random number between 0 and 1 (Eg:0.something..)

Get Browser Type using Javascript

Get Browser Type using Javascript

<script language="JavaScript"
type="text/javascript">

function getBrowserType() {
var bo = navigator.userAgent;
var browserType = "unknown";
if (bo.indexOf("Opera") > -1) {
browserType = "Opera";
} else if (bo.indexOf("Safari") > -1) {
browserType = "Safari";
} else if (bo.indexOf("Konqueror") > -1) {
browserType = "Konqueror";
} else if (bo.indexOf("Gecko") > -1) {
browserType = "Mozilla";
} else if (bo.indexOf("MSIE") > -1) {
browserType = "Internet Explorer";
}
//window.alert(browserType);
return browserType;
}
</script>


To get version no you may use the following (but have to exact version no):
window.alert(navigator.userAgent);


Result might look like:

Mozilla/5.0 (Windows; U; Windows NT 5.1; en;
rv:1.8.0.3) Gecko/20060426 Firefox 1.5.0.3
Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US;
rv:1.4) Gecko/20030619 Netscape/7.1 (ax)
Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;
SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322;
.NET CLR 2.0.50727)
Mozilla/5.0 (compatible; Konqueror/3.4; FreeBSD)
KHTML/3.4.2 (like Gecko)
Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en)
AppleWebKit/418 (KHTML, like Gecko)
Safari/417.9.3
Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en)
AppleWebKit/312.8 (KHTML, like Gecko)
Safari/312.6
Opera/9.00 (Windows NT 5.1; U; en)
Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;
en) Opera 9.00



Currently the following type of browser are available:

Internet Explorer
Mozilla Browsers
Konqueror (KDE)
Apple Safari
Opera Browser

Cache dataset in asp.net

Cache dataset in asp.net
===================


use the namespace : System.Web.Caching.Cache

Add dataset to cache :
Cache.Insert("yourDataSet",ds,null,DateTime.Now.AddSeconds(15),System.TimeSpan.Zero);

Remove dataset from cache:
Cache.Remove("yourDataSet");

load dataset from cache:

if(Cache["CustomersDataSet"] != null) {
ds = (DataSet)Cache["yourDataSet"];
}
else {
//logic to insert dataset to cache (i.e. load dataset and put it into cache)
}

Saturday, September 22, 2007

ASP.NET 2 life cycle listing

Application: BeginRequest
Application: PreAuthenticateRequest
Application: AuthenticateRequest
Application: PostAuthenticateRequest
Application: PreAuthorizeRequest
Application: AuthorizeRequest
Application: PostAuthorizeRequest
Application: PreResolveRequestCache
Application: ResolveRequestCache
Application: PostResolveRequestCache
Application: PreMapRequestHandler
Page: Construct
Application: PostMapRequestHandler
Application: PreAcquireRequestState
Application: AcquireRequestState
Application: PostAcquireRequestState
Application: PreRequestHandlerExecute
Page: AddParsedSubObject
Page: CreateControlCollection
Page: AddedControl
Page: AddParsedSubObject
Page: AddedControl
Page: ResolveAdapter
Page: DeterminePostBackMode
Page: PreInit
Control: ResolveAdapter
Control: Init
Control: TrackViewState
Page: Init
Page: TrackViewState
Page: InitComplete
Page: LoadPageStateFromPersistenceMedium
Control: LoadViewState
Page: EnsureChildControls
Page: CreateChildControls
Page: PreLoad
Page: Load
Control: DataBind
Control: Load
Page: EnsureChildControls
Page: LoadComplete
Page: EnsureChildControls
Page: PreRender
Control: EnsureChildControls
Control: PreRender
Page: PreRenderComplete
Page: SaveViewState
Control: SaveViewState
Page: SaveViewState
Control: SaveViewState
Page: SavePageStateToPersistenceMedium
Page: SaveStateComplete
Page: CreateHtmlTextWriter
Page: RenderControl
Page: Render
Page: RenderChildren
Control: RenderControl
Page: VerifyRenderingInServerForm
Page: CreateHtmlTextWriter
Control: Unload
Control: Dispose
Page: Unload
Page: Dispose
Application: PostRequestHandlerExecute
Application: PreReleaseRequestState
Application: ReleaseRequestState
Application: PostReleaseRequestState
Application: PreUpdateRequestCache
Application: UpdateRequestCache
Application: PostUpdateRequestCache
Application: EndRequest
Application: PreSendRequestHeaders
Application: PreSendRequestContent

Saturday, September 1, 2007

Reinstall IIS using command (for coders)

Reinstall IIS using command (for coders)

D:\WXPOS\Microsoft.net\Framework\v2.0.50727> aspnet_regiis -i
>
iisreset

use aspnet_regiis /? for help

tic tac toe (tic-tac-toe) in C

tic tac toe in C
============


#include <stdio.h>
#include <graphics.h>
#include <stdlib.h>
#include <conio.h>


int rowcol[9]={1,2,3,4,5,6,7,8,9};

void main(){

int gdriver,gmode,errorcode;
int is;
int i,temp;
int bool;
char ch[2];
bool=0;
gdriver=EGA;
gmode=EGAHI;
/*initialize the graphics driver*/
initgraph(&gdriver,&gmode,"");
/* error handling for graphics driver */
errorcode = graphresult();
if ( errorcode != grOk ) {
printf("Graphics Error \n %s",grapherrormsg(errorcode));
printf("\n Press any key to halt:");
getch();
exit(1);
}

setbkcolor(11);
setcolor(1);
settextstyle(0,0,2);
outtextxy(40,40,"WELCOME TO THE GAME OF SUNCHOKRI");
/*
for(is=1000;is>500;is--){
sound(is);
delay(250);
}
nosound();
*/

setcolor(12);

outtextxy(150,120,"BY ----");
/* preloader logic in c programming */
setcolor(1);
i=0;
while(i!=600){
preloader(i);
delay(300);
i++;
}


sleep(2);
cleardevice();
mainscreen();
positionofx();
chanceofplayer(bool);

/*if q is pressed quit the game */
while((*ch=getch())!='q') {
/*if n is pressed new game*/
if(*ch=='n'){
for(is=0;is<9;is++){
rowcol[is]=is+1;
}
bool=0;
cleardevice();
mainscreen();
positionofx();
chanceofplayer(bool);
}

temp=atoi(ch) ;
if (temp==0){
}
else {

if (rowcol[temp-1]==11 rowcol[temp-1]==22){
}
else {
if(bool==0){
rowcol[temp-1]=11;
}
else
{
rowcol[temp-1]=22;
}
cleardevice();
mainscreen();
positionofx();
if(bool==0){
bool=1;
}
else
{
bool=0;
}
chanceofplayer(bool);
}
}
}
/*
getch(); */

/*closing or deallocating graphic driver*/
closegraph();
}

/*main background screen*/
mainscreen() {
setbkcolor(12);
rectangle(10,10,620,250);
setcolor(14);
settextstyle(0,0,4);
outtextxy(35,300,"S U N C H O K R I");
setcolor(9);
settextstyle(0,0,2);
outtextxy(105,220,"Player 1 :11 Player 2 :22");
setcolor(15);
settextstyle(0,0,1);
outtextxy(0,0,"Author: ----SG");
/* small rectagle for sunchokri.. */
setcolor(WHITE);
rectangle(20,20,300,200);
rectangle(50,50,90,80);
rectangle(100,50,140,80);
rectangle(150,50,190,80);

rectangle(50,120,90,90);
rectangle(100,120,140,90);
rectangle(150,120,190,90);

rectangle(50,160,90,130);
rectangle(100,160,140,130);
rectangle(150,160,190,130);


outtextxy(399,60,"q TO QUIT GAME");
outtextxy(399,80,"n FOR NEW GAME");
}

/* logic of various functions in c */
preloader(int i) {
outtextxy(i,300,"");
}

positionofx(){
char x[10];
setcolor(YELLOW);

itoa(rowcol[8],x,10);
/*last row */
outtextxy(165,140,x);
itoa(rowcol[7],x,10);
outtextxy(115,140,x);
itoa(rowcol[6],x,10);
outtextxy(65,140,x);

/*second last row */
itoa(rowcol[5],x,10);
outtextxy(165,100,x);
itoa(rowcol[4],x,10);
outtextxy(115,100,x);
itoa(rowcol[3],x,10);
outtextxy(65,100,x);

/*first row */
itoa(rowcol[2],x,10);
outtextxy(165,60,x);
itoa(rowcol[1],x,10);
outtextxy(115,60,x);
itoa(rowcol[0],x,10);
outtextxy(65,60,x);
}

chanceofplayer(int bool1 ) {
char s[1];
if(bool1==0){
bool1=1; }
else
{
bool1=2; }

itoa(bool1,s,10);
setcolor(4);
outtextxy(33,33,"Turn of player : ");
outtextxy(173,33,s);

/* logic for winning the game */
if((rowcol[0]==11 && rowcol[1]==11 && rowcol[2]==11)(rowcol[3]==11 && rowcol[4]==11 && rowcol[5]==11)(rowcol[6]==11&&rowcol[7]==11&&rowcol[8]==11)(rowcol[0]==11&&rowcol[4]==11&&rowcol[8]==11)(rowcol[2]==11&&rowcol[4]==11&&rowcol[6]==11)){
outtextxy(399,100, "1 WINS");
sound(350);
delay(2000);
nosound();
}
else if((rowcol[0]==22&&rowcol[1]==22&&rowcol[2]==22)(rowcol[3]==22&&rowcol[4]==22&&rowcol[5]==22)(rowcol[6]==22&&rowcol[7]==22&&rowcol[8]==22)(rowcol[0]==22&&rowcol[4]==22&&rowcol[8]==22)(rowcol[2]==22&&rowcol[4]==22&&rowcol[6]==22)){
outtextxy(399,100, "2 WINS");
sound(350);
delay(2000);
nosound();
}
else if((rowcol[0]==22&&rowcol[3]==22&&rowcol[6]==22)(rowcol[1]==22&&rowcol[4]==22&&rowcol[7]==22)(rowcol[2]==22&&rowcol[5]==22&&rowcol[8]==22)){
outtextxy(399,100, "2 WINS");
sound(350);
delay(2000);
nosound();
}
else if((rowcol[0]==11&&rowcol[3]==11&&rowcol[6]==11)(rowcol[1]==11&&rowcol[4]==11&&rowcol[7]==11)(rowcol[2]==11&&rowcol[5]==11&&rowcol[8]==11)){
outtextxy(399,100, "1 WINS");
sound(350);
delay(2000);
nosound();
}
else{
outtextxy(399,100,"NO RESULT");
}
}

shared files program in C

shared files program in C

/* shared file example 1 */


#include <fcntl.h>
#include <stdio.h>


main()
{
int fp;
char buff[20];
fp=open("testfile",O_RDONLY);
if(fork()==0)
{
read(fp,buff,10);
buff[10]=0;
puts(buff);
}

else
{
wait(0);
read(fp,buff,10);
buff[10]=0;
puts(buff);
}

}

/*shared file example 2 */

#include <fcntl.h>
#include <stdio.h>


main()
{
FILE *fp;
char buff[20];
fp=fopen("testfile","r");
if(fork()==0)
{
fgets(buff,10,fp);
buff[10]=0;
puts(buff);
}

else
{
wait(0);
fgets(buff,10,fp);
buff[10]=0;
puts(buff);

}

}

/*lock file */


#include <fcntl.h>
#include <stdio.h>


main()
{
int fd;
fd=open("Lockset",O_RDWR);
lockf(fd,F_LOCK,0);
printf("Process %d locked the file \n",getpid());
if(fork()==0)
{
lockf(fd,F_LOCK,0);
printf("Process %d locked the file \n",getpid());
printf("Child Process is over\n");
}

else
{
sleep(5);
printf("Process %d is over\n",getpid());

}

}

semaphore program in C

Semaphore program in C

/* basic semaphore example 1 */

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <stdio.h>


main()
{
int sid;
int key,nsem;
key=(key_t)0x30;
nsem=1;
sid=semget(key,nsem,IPC_CREAT0777);
printf("\nSemaphore was created with the id = %d\n",sid);

}

/* basic semaphore example 2*/

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <stdio.h>


main()
{
int sid;
int key,nsem;
key=(key_t)0x30;
nsem=1;
sid=semget(key,nsem,IPC_CREAT0666);
printf("\nSemaphore was created with the id = %d\n",sid);
sleep(15);
semctl(sid,0,IPC_RMID,0);
}


/* readers */

#include <sys/types.h>
#include <sys/sem.h>
#include <sys/ipc.h>
#include <stdio.h>


void sem_wait (int);
void sem_signal(int);


main(){
int rdcnt,wrt,mutex;
key_t rdkey=0x20;
key_t wrkey=0x30 ;

rdcnt = semget(rdkey,1,0666IPC_CREAT);
wrt = semget(wrkey,1,0666IPC_CREAT);
mutex = semget(0x40 ,1,0666IPC_CREAT);

semctl(mutex,0,SETVAL,1);
printf("\nStarting to Read.....");
sem_wait(mutex);
sem_signal(rdcnt);
sleep(10);
printf("\nReading Finished");
sem_wait(rdcnt);
sem_signal(mutex);

}


void sem_wait(int id){
struct sembuf buf = { 0,-1,0};
semop(id,&buf,1);
}

void sem_signal(int id){
struct sembuf buf = { 0,1,0};
semop(id,&buf,1);


}

screen saver in C random circles lines - c program

screen saver in C random circles lines - c program

#include <stdio.h>
#include <graphics.h>
#include <stdlib.h>
#include <conio.h>


char ch;
/****************************************/
/* for line */
int lrandx, lrandy, lrandxx, lrandyy;
/* for rectangle */
int rrandx, rrandy, rrandxx, rrandyy;
/* for circle*/
int crandx, crandy, cradius;
/* random colour and shape generation */
int shape;
int col;

int gdriver,gmode,errorcode;
/*****************************************/
void main(){
gdriver=EGA;
gmode=EGAHI;
/*initialize the graphics driver*/
initgraph(&gdriver,&gmode,"");
/* error handling for graphics driver */
errorcode = graphresult();
if (errorcode != grOk ) {
printf("Graphics Error \n %s",grapherrormsg(errorcode));
printf("\n Press any key to halt:");
getch();
exit(1);
}
/* setting initiation of text and background color */
initialscreen();
while (!kbhit()) /* do nothing */ {
sleep(0.5);
mainscreen();
/*
outtextxy(133,44,"Sss");
*/
}
/*closing or deallocating graphic driver*/
closegraph();
}


/*main background screen*/
mainscreen() {
shape=rand()%3;
col=rand() % 14;
if (shape==0) {
rrandx=rand() % 600;
rrandy=rand() % 600;
rrandxx=rand() % 800;
rrandyy=rand() % 800;
setcolor(col);
rectangle(rrandx, rrandy, rrandxx, rrandyy);
}
else if (shape==1) {
lrandx=rand() % 200;
lrandy=rand() % 200;
lrandxx=rand() % 200;
lrandyy=rand() % 200;
setcolor(col);
line(lrandx, lrandy, lrandxx, lrandyy);
}
else {
crandx=rand() % 600;
crandy=rand() % 600;
cradius=rand() % 100;
setcolor(col);
circle(crandx, crandy, cradius);
}
return 0;
}

initialscreen() {
setbkcolor(4);
setcolor(1);
settextstyle(0,0,2);
outtextxy(40,40,"SCREEN SAVER...");
setcolor(11);
outtextxy(150,120,"---- computer bapu");
sleep(2);
cleardevice();
return 0;
}

character generation in C - program

Character generation in C - program

#include <graphics.h>
#include <conio.h>
#include <math.h>
void generatecharback();
void generatechar(char);
void main()
{
int gdriver, gmode;

gdriver=DETECT;
gmode=EGAHI;
initgraph(&gdriver,&gmode,"");
setbkcolor(4);
generatecharback();
generatechar('B');
outtextxy(203, 200, "char generation");
getch();
closegraph();
}

void generatecharback(){
int i=0;
int j=0;
for(i=0;i<=7;i++){
for(j=0;j<=7;j++){
putpixel(i+100,j+100,8);
}
}
}
void generatechar() {
int charray[1][65]={{1,1,1,1,1,1,0,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,1,1,1,0,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0}};
int i,j,k;
k=0;
for(i=0;i<=7;i++){
for(j=0;j<=7;j++){
if(charray[0][k]==1){
putpixel(j+100,i+100,WHITE);
}
k++;
}
}
}

forking i.e examples in C (fork program)

forking i.e example in C (fork program)
===============================


/*forking example 1 */
#include<sys/types.h>
main()
{
int i;
int j;
fork();

printf("\n%d\n",getpid());
printf("\n%d\n",getppid());
getchar();

}

/*forking example 2 */
main()
{
int i=fork();
if(i==0)
{
printf("I'm the child.My PID is %d\n",getpid());
printf("And my parent's PID is %d\n",getppid());
}
else
{
printf("I'm the Parent.My PID is %d\n",getpid());
printf("And my parent's PID is %d\n",getppid());
wait();
}
exit(0);
}


/*forking example 3 */

main()
{
int i=fork();
if(i==0)
{
printf("I'm the child.My PID is %d\n",getpid());
printf("And my parent's PID is %d\n",getppid());

sleep(5);

printf("I'm the child.My PID is %d\n",getpid());
printf("And my parent's PID is %d\n",getppid());
}
else
{
sleep(2);
printf("I'm the Parent.My PID is %d\n",getpid());
printf("And my parent's PID is %d\n",getppid());
}
}

/*forking example 4 */

#include<sys/types.h>
main()
{
int j;
int pid=fork();
if(pid==0)
for(j=0;j<30000;j++)
printf("\n%10d\tChild",j);

else
for(j=0;j<30000;j++)
printf("\n%10d\tParent",j);
}


/*forking example 5*/

#include<sys/types.h>
main()
{
int j;
if(fork()==0)
{
printf("\nFirst Child Executing");
for(j=0;j<10000;j++)
;
printf("\nFirst Child is dying now\n" );
}
else
{
if(fork()==0)
{
printf("Second Child Executing");
for(j=0;j<10000;j++)
;
printf("\nSecond Child is dying now\n" );
}
else
{

printf("\nI'm the BOSS here\n");
printf("\nThe first child to die is %d\n",wait(0));

for(j=0;j<10000;j++)
;
printf("\nThe Second child to die is %d\n",wait(0));

printf("But nothing is in my hand!\n");
}

}

}

/*forking example 6*/

main()
{
int pid;
int i=10;
pid=fork();
if(pid==0)
{
printf("\nThe value of I in child is \t%d\n",i);
i+=10;
printf("\nThe (inc)value of I in child is \t%d\n",i);

}

else
{
wait(0);
printf("\nThe value of I in parent is \t%d\n",i);
}
}

/*forking example 7*/

main()
{
int i=10;
if(fork()==0)
printf("\nThe address of i in child is %X \n",&i);
else
printf("\nThe address of i in parent is %X \n",&i);

}


/*forking example 8*/

#include<sys/types.h>
main()
{
if(fork()>0)
{
printf("I'm the parent\n");
sleep(10);
}


}


Do's and Don't in Web Design

Do's and Don't in Web Design
=======================


Technology Related
================


Do try to make the site using only divs and css (Don't use table tags atall!!)
Do try to use AJAX whereever applicable
Do follow Web 2 style!! (big and clear navigation..)
Do try to use a small image and use it as a background of a div/page .. i.e ... use repeat property so that the image may fill a large div and this will load very fast (Eg: 2 x 10 size image for gradient effect)
Do test your application in 3 browser before deploying (Firefox, Internet Explorer 6 and Internet Explorer 7 ---- If a site looks ok in firefox its most likely that it would run everywhere else)
Do use web design tools like macromedia dreamweaver.
Do try to place images and media files in folders and subfolders
Do avoid use of activex components
Do use flash swf file supporting version 6.0. (flash 6.0. is more common word wide) although the latest versions are rapidly gaining popularity.
Don't overuse ajax
Don't use animation too much..only use animation wherever relevant
Do try to use multiple themes, which can be selected by the user (red,blue,back,green...check msn site)
Do try to use the new generation technique of using xml, xslt (for advance users) including templating and skinning (is more applicable for very large sites which is partly static and dynamic [Is currently used in various cms packages])
Do use cross-platform javascripts/dhtml for varous purposes (Eg: validation, calling background sound, animation, cookie setting etc)
Do try to use preloaders if the site is heavy!!..
Do avoid popups!!..


General
=======
Do close popup screens
Do stop sounds
Don't try to mislead seach engines
Don't try to misleadingly attract visitors
Do register your site
Do read the stats
Don't count hits (may be a refresh..)
Do put contact info on your pages (clearly!!!)
Do try to use robots (robot.txt is used by search engines to get a list of all the directories/files you want search engine to index)
Do Try to use domain to come popular (In subdomains there are lots of restrictions)

Content
=======
Do know your audience
(Whenever you make a site target some set of people Eg: religion, programming etc)
Do provide topics
(divide a particular page into topics Eg: introduction, explaination etc..)
Do briefly describe your things
Do use correct spelling
Don't use meaningless words
Don't use jargon
(words used by particular groups but hard to understand by many)
Don't write technical
Do use important text on your main page
Do present the issues right away (good representation of data here)
Do use a descriptive title (very important for search engines)
Do use small pages (avoid long scrollers..)
Don't split topics (don't divide a topic into 100 sub topics..)
Do use implicit text for your links
(Try to write your text in such a way that a link is a natural part of
the sentence.)
Do comment on your links
Do update your pages
Do show date of update
Do ask for feedback
Don't show any page under construction (try to be complete and then publish)

Navigation
==========

Do use explicit addressing (try to specify up, down, left right, previous etc kink of links)
Do check your links (use a tool to check it for u..)
Don't change links (link renaming a file since it might be indexed by the search engine or may be a link at other site)
Do always supply textual links
Do suply a link to home
Do use navigational aids at the top and the bottom
Do use a table of contents
Do create a “what's new” page
Do use short routes
Do keep menu items related
Don't link to irrelevant pages
Don't repeat links too often
Don't use ambivalent navigation (it should not be a spagattei/noodles kind of links!!)
Don't create dead end pages (page without a link)
Don't frame other sites (don't load other site within a frame..the site won't go with the look and feel)


Design
=====

Do use a consistent look and feel
Do use recurring visual element
Don't use dark backgrounds
Don't cram your pages
Don't push your table out of the screen
Don't overuse frames
Do vertical align the content of table cells
Don't mix horizontal aligning


Bandwidth
=========

Do use few colors in your GIF's
Do use high compression in JPEG
Do reserve space for images
Do provide thumbnails for large images
Do reuse images
Don't reference images from other sites
Do provide size informationo
Don't use large textual images
Don't use wordprocessors


Presenting Text
===============

Don't use blink (old days..)
Don't use columns for text
Don't use small serif letters
Don't use all capitals
Don't overuse bold text
Don't overuse italics
Don't use small fonts
Don't use too many fonts
Do use punctuation
Don't hide your links
Do use all lowercase or all uppercase links
Do separate adjacent textual links
Do limit the size of predefined text
Do limit the width of text
Do use textual dates
Do provide a visual email address


Images and colors
=================

Do use transparency
Do use interlacing
Don't use too many images
Do make your graphics reproducible
Do break up images
Do combine backgroundimages and background-colours
Do use a browser safe palette
Don't use too many colors
Don't override only one standard colour

Compatibility
===============
Do supply alt's for your images
Do use alt text for areas
Do use alt text for areas
Do use NOFRAMES
Do use comments for javascript
don't be selective with browsers
Do test Java applets with all browsers
Do test with fewer screen colors
Do test with lowres
Do validate
Don't rely on plugins
Do check for browser version
Do warn for important cookies
Do offer alternative views



-taken from various resources plus my additions..

Monday, August 27, 2007

validate rss and atom

validate rss and atom
================


http://feedvalidator.org/

http://rss.scripting.com/

http://www.walidator.com/

http://www.ldodds.com/rss_validator/

http://feeds.archive.org/validator

http://www.ldodds.com/rss_validator/1.0/validator.html

http://aggregator.userland.com/validator

http://www.w3.org/RDF/Validator/ (RDF validator)

Web Syndication with RSS and ATOM

Web Syndication with RSS and ATOM
===========================



Syndication lets sites share information across the Web, making it easy to do things like display headlines from a site or collection of sites. Most of the syndicated feeds are written in RSS, a simple XML vocabulary (in several varieties) for summarizing information about a site. Several popular flavors of RSS are leading the pack, with upstart Atom growing in acceptance

Eg: news feeds you might find in news site, blogs etc.

There are accepted standards for syndication:


1) RSS

* RSS 0.91 (Rich Site Summary) and RSS 0.92
* RSS 1.0 (RDF Site Summary)
* RSS 2.0 (Really Simple Syndication)


2) ATOM


Formats:

For RSS 0.91
============


<rss version="0.91">

<channel>

<title>Computer Bapus Post</title>

<link>http://computerbapu.blogspot.com</link>

<description> All computer related discussions</description>

<language>en-us</language>

<image>

<url>http://computerbapu.blogspot.com/myimage.jpg</url>

<title>C# hello world</title>

<link>http://computerbapu.blogspot.com</link>

</image>

<item>

<title>C# hello world</title>

<link>http://computerbapu.blogspot.com</link>

<description>console.writeline("i am good");</description>

</item>

</channel>

</rss>

Explaination :

title
A descriptive title for this channel. This should usually be the same as the content of the HTML element title on your main site page
(maximum length : 100)

link
A URI for the channel. This should be a link to the web site that originates the feed
(maximum length is 500 characters)

description
A description of the channel, usually answering the question "What's this site all about?" Limited to 500 characters.


copyright
Copyright notice for the channel

docs
Documentation for the RSS format used by the channel

lastBuildDate
Last time channel content changed, in RFC 822 format, Sat, 01 Jan 05 00:00:27 PST (see http://www.ietf.org/rfc/rfc822.txt)

managingEditor
Email address of managing editor for the channel

pubDate
Publication date of channel, in RFC 822 format, Sat, 01 Jan 05 00:00:27 PST (see http://www.ietf.org/rfc/rfc822.txt)

rating
Platform for Internet Content Selection (PICS) rating (http://www.w3.org/PICS/)

skipDays
Days to skip reading channel

skipHours
Hours to skip reading channel

textInput
A text input box for the channel, such as a search box (required children include title, description, name, and link)

webMaster
Email address of webmaster for the channel



For RSS 1.0 format
=================


XML API

<?xml version="1.0" encoding="UTF-8"?>

<rdf:RDF xmlns="http://purl.org/rss/1.0" xmlns:rdf="http://www.w3.org/1999/02/22

-rdf-syntax-ns#">

<channel rdf:about="http://computerbapu.blogspot.com/computerbapu.rss">

<title>Computer bapu</title>

<link>http://computerbapu.blogspot.com</link>

<description>Computer help</description>

<items>

<rdf:Seq>

<rdf:li rdf:resource="http://computerbapu.blogspot.com/myhelp.html"/>

</rdf:Seq>

</items>

</channel>

<item rdf:about="http://computerbapu.blogspot.com/myhelp.html">

<title>C# snippet for email</title>

<link>http://computerbapu.blogspot.com/email.html</link>

<description>hello world ()...</description>

</item>

</rdf:RDF>



Explaination:

rdf:RDF
The rdf:RDF element from the RDF namespace (http://www.w3.org/1999/02/22-rdf-syntax-ns#) is the document element. This element must have exactly one channel child and one or more item children (these elements are in the default namespace, http://purl.org/rss/1.0). The rdf:about attribute on channel, from the RDF namespace, identifies the feed with a URI.

title
A descriptive title for this channel.

link
A URI for the channel.

description
A description of the channel.

items
Contains the RDF elements Seq and li. The resource attribute on rdf:li contains a URI that identifies an item used later in the document

Two other possible children of channel are image and textinput, which link by means of rdf:resource attributes to other image and textinput elements, optionally used in the document as children of rdf:RDF (i.e., you can have one without the other). The image element links a graphic to the channel and must contain the trio title, link, and url; the textinput element contains a script or form that relates to the site and contains title, link, name, and description elements.


For RSS 2.0 format (quite popular now - successor of rss 0.91.)
===================================================


Example:

<rss version="2.0">

<channel>

<title>computer bapu</title>

<link>http://computerbapu.blogspot.com</link>
<pubDate>Mon, 05 Feb 2007 0:00:01 GMT</pubDate>

<description> computer help</description>


<item>

<title>RSS Help</title>

<link>http://computerbapu.blogspot.com/rsshelp.html</link>

<description>Latest News Feeds....</description>

</item>

<item>

<title>Atom Help</title>

<link>http://computerbapu.blogspot.com/atomhelp.html</link>

<description>Latest RSS News Feeds....</description>

</item>


</channel>

</rss>





Explaination:

Child element of channel:

title
Title of channel
(Required)

link
Link to channel
(Required)

description
Description of channel
(Required)

language
Language code for channel
(optional element)

image
Image that represents the channel (required children url, title, and link; optional children description, width, and height)
(optional element)

copyright
Copyright notice for the channel
(optional element)

managingEditor
Email address of managing editor
(optional element)

webMaster
Email address of webmaster
(optional element)

pubDate
Publication date of channel in RFC 822 format, Sat, 01 Jan 05 00:00:27 PST; though not specified in RFC 822, a four-digit year is allowed (see http://www.ietf.org/rfc/rfc822.txt)
(optional element)

lastBuildDate
Last time channel content changed in RFC 822 format, Sat, 01 Jan 05 00:00:27 PST; though not specified in RFC 822, a four-digit year is allowed (see http://www.ietf.org/rfc/rfc822.txt)
(optional element)

rating

Platform for Internet Content Selection (PICS) rating (http://www.w3.org/PICS/)
(optional element)

docs
Documentation for the RSS format used by channel
(optional element)

textInput
A text input box for the channel, such as a search box (required children include title, description, name, and link)
(optional element)

skipDays
Days to skip reading channel
(optional element)

skipHours
Hours to skip reading channel
(optional element)

category
One or more channel categories
(optional element)

generator
Name of generator program
(optional element)

cloud
Specifies a protocol for publishing and subscribing to feeds
(optional element)

ttl
Time to live in minutes
(optional element)


Child element of item:


title
Title of item

link
Link to item

description
Description of item

author
Email address of author of item (optional element)

category
One or more item categories (optional attribute domain)
(optional element)

comments
URL for comment page for item
(optional element)

enclosure
Describes an object attached to item (required attributes url, length, and type)
(optional element)

guid
Globally unique identifier
(optional element)

pubDate
Publication date in RFC 822 format
(optional element)

source
RSS channel the item came from (required attribute url)
(optional element)


Format of ATOM :
==============


<feed version="0.3" xmlns="http://purl.org/atom/ns#" xml:lang="en">

<title>Computer Bapu</title>

<link rel="alternate" type="text/html"

href="http://computerbapu.blogspot.com/"/>

<author>

<name>Computer Bapu SG</name>

</author>

<tagline>This discusses about computer topics</tagline>

<modified>2007-05-14T08:56:00-01:00</modified>

<entry>

<title>C# snippet</title>

<link rel="alternate" type="text/html"

href="http://computerbapu.blogspot.com/mySnippet.html"/>

<id>http://computerbapu.blogspot.com/mySnippet.html</id>

<issued>2007-04-14T08:56:00-01:00</issued>

<modified>2007-05-14T08:56:00-01:00</modified>

</entry>

</feed>


Title: title of the document. There can be only one title.
link: Link of the resource. There can be multiple links. Type denotes media type.
Author: Author of the resource. There can be one author container within which there can be name, url, email
tagline : feeds description

show detailed error in asp.net 2.0 web.config

show detailed error in asp.net 2.0 web.config
====================================


In web.config do the following

<customErrors mode="Off" />

This is handy for developers and testers in case when they are unable to exactly find the cause of an error. When in production this should not be used since it will show the entire detail to the laymen.

In such case use <customErrors mode="On"> to hide the detailed error.

You might want to keep show the error when run locally and hide the error when run remotely. You may achieve this using <customErrors mode="RemoteOnly">


Also if you want to redirect to a particular page when there is a error then you might use the below option:

<customErrors mode="On" defaultRedirect="ErrorTemplate.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>


what a basic hardware technician / pc technician must know

what a basic hardware technician / pc technician must know :

BASICS:

Hardware Industry
General Concepts about Hardware Parts
Hardware Jargon
Hardware components (detail discussion)
- motherboards, cpu, ram, drives, Add-on Cards, BIOS details, different types of cards available, cabinets etc
Power Supply
Peripherals latest rates and commercial information
Handling hardware components
Hardware repairing and assembling tools
Peripheral Drivers


HARDWARE INSTALLATIONS:

Hardware Assembling
Assembling Steps and Procedures
Testing of H/W before Assembling
Installation of External Peripherals such as printers, modem, LAN card, joystick, UPS, scanner, webcam etc.
Core Details:
Fixing of Mother Board, Cards etc.
Connecting Jumper Wires, Checking of AC/DC voltage, Serviceability Checks, Wire setting, Power LED-ON , Speaker Beep, Memory Testing, Error Codes.
Upgrading old pc into latest pc

PREVENTIVE MAINTAINANCE:

Hardisk Maintenance, Printer Maintenance, other peripheral maintenance briefings
Use of UPS
Use of Stabilizer
Cleaning Techniques: Internal System Components & Peripheral Components
Antivirus software

TROUBLESHOOTING:

Do and Don’t of Assembling
Various Jumpers/switches
ROM BIOS configuration
Compatible Hardware Part identification to prevent mismatch with older pc or pc with different motherboard or cpu
CD ROM & other peripheral repairing (core)
Printer cartrage fitting
Checking of COM and LPT ports
Connecting PDA’s to computer via port
Other repairing Techniques
Finding defective components (most probable problems for a particular fault)
Repairing boot faults
Finding input device problem, drives problem, power problems, modem problems, boot problems, adapter card and pc card problem etc.
Partitioning techniques
OS installations, formatting, dual boot
Modem , sound and display driver installtion
Defragmentation and Scandisk
Troubleshooting utilities and software
Troubleshooting remotely and handling people
Data Transfer Techniques


NETWORK BASICS:

LAN setup
Hardisk data transfer
Internet Connection – dial-up, cable connection, using mobile phone
cabling, labtop overview


Get a A+ certification in short. You may also give an exam at brainbench and check whether you pass / fail..The above you can easily cover in 1 and a half month or even less


php simple paging example

php simple paging example
======================


The below code is self explanatory for a coder

<?
function Connect() {

$hostname = "localhost";
$database = "mmm";
$db_login = "";
$db_pass = "";

$ad_login = "";
$ad_pass = "";


$dbase_link = mysql_connect($hostname, $db_login, $db_pass) or die("Could not connect");
mysql_select_db($database) or die("Could not select database");

}
?>

<?php

//Set the page size
$PageSize = 10;
$StartRow = 0;

//Set the page no
if(empty($_GET['PageNo'])){
if($StartRow == 0){
$PageNo = $StartRow + 1;
}
}else{
$PageNo = $_GET['PageNo'];
$StartRow = ($PageNo - 1) * $PageSize;
}

//Set the counter start
if($PageNo % $PageSize == 0){
$CounterStart = $PageNo - ($PageSize - 1);
}else{
$CounterStart = $PageNo - ($PageNo % $PageSize) + 1;
}

//Counter End
$CounterEnd = $CounterStart + ($PageSize - 1);
?>

<html>
<head>
<title>Paging Example By Nasa</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" href="include/style.css" type="text/css">
</head>
<?php

connect();
//query trick
$strSQL = "select * from bike where Type='$type'
AND Brand='$brand' AND City='$city' ORDER BY area LIMIT $StartRow,$PageSize";

$result = mysql_query($strSQL) or die("Query failed");
$TRecord = mysql_query("SELECT * FROM bikes");

//Total of record
$RecordCount = mysql_num_rows($TRecord);

//Set Maximum Page
$MaxPage = $RecordCount % $PageSize;
if($RecordCount % $PageSize == 0){
$MaxPage = $RecordCount / $PageSize;
}else{
$MaxPage = ceil($RecordCount / $PageSize);
}
?>
<body>
<table width="100%" border="0" class="InternalHeader">
<tr>
<td width="24%">LIST.....</td>
<td width="76%">
<div align="right">
<?php print "$RecordCount record(s) founds - You are at page $PageNo of $MaxPage" ?></div>
</td>
</tr>
</table>
<br>
<table width="100%" border="0" class="NormalTableTwo">
<tr>
<td width="4%">ID</td>
<td width="36%">NAME ID</td>
<td width="20%">CONTACT</td>
<td width="20%">PHONE</td>
</tr>
<?php
$i = 1;
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$bil = $i + ($PageNo-1)*$PageSize;
?>
<tr>
<td width="4%"><?php echo $bil ?></td>
<td width="36%"><?php echo $row["ID"] ?></td>
<td width="20%"><?php echo $row["Name"] ?></td>
<td width="20%"><?php echo $row["contact"] ?></td>
<td width="20%"><?php echo $row["phone"] ?></td>
</tr>
<?php
$i++;
}?>
</table><br>
<table width="100%" border="0" class="InternalHeader">
<tr>
<td>

<div align="center">
<?php
//Print First & Previous Link is necessary
if($CounterStart != 1){
$PrevStart = $CounterStart - 1;
print "<a href=ok1.php?PageNo=1>First </a>: ";
print "<a href=ok1.php?PageNo=$PrevStart>Previous </a>";
}
print " [ ";
$c = 0;

//Print Page No
for($c=$CounterStart;$c<=$CounterEnd;$c++){
if($c < $MaxPage){
if($c == $PageNo){
if($c % $PageSize == 0){
print "$c ";
}else{
print "$c ,";
}
}elseif($c % $PageSize == 0){
echo "<a href=ok1.php?PageNo=$c>$c</a> ";
}else{
echo "<a href=ok1.php?PageNo=$c>$c</a> ,";
}//END IF
}else{
if($PageNo == $MaxPage){
print "$c ";
break;
}else{
echo "<a href=ok1.php?PageNo=$c>$c</a> ";
break;
}//END IF
}//END IF
}//NEXT

echo "] ";

if($CounterEnd < $MaxPage){
$NextPage = $CounterEnd + 1;
echo "<a href=ok1.php?PageNo=$NextPage>Next</a>";
}

//Print Last link if necessary
if($CounterEnd < $MaxPage){
$LastRec = $RecordCount % $PageSize;
if($LastRec == 0){
$LastStartRecord = $RecordCount - $PageSize;
}
else{
$LastStartRecord = $RecordCount - $LastRec;
}

print " : ";
echo "<a href=ok1.php?PageNo=$MaxPage>Last</a>";
}
?>
</div>
</td>
</tr>
</table>
<?php
mysql_free_result($result);
mysql_free_result($TRecord);
?>
</body>
</html>

Quickly make a deploy folder using ASP.NET 2.0.

Quickly make a deploy folder using ASP.NET 2.0.
=======================================


run the below command a folder will be created (as specified). Also mysite is the path of your website

asp_compiler -v mysite c:\folder -f -u

Register an activex component

Register an activex component

look for regsvr32.exe in system/system32 folder in windows (note down the path)

Open dos prompt and do it!

C:\system32>regsvr32 c:\youractivex.ocx

A messagebox will appear if the ocx gets registered.

List tables in ms sql server

List tables in ms sql server
=====================


For ms sql
sp_help

For my sql it is
show tables

List tables in ms sql server

List tables in ms sql server
=====================


For ms sql
sp_help

For my sql it is
show tables

List fields in ms sql server

List fields in ms sql server
=====================


for my sql:
describe tablename

for ms sql server:
sp_help tablename

list database in ms sql server

list database in ms sql server
=======================


Just type out following command in ms sql server query analyzer

sp_databases

For My sql type out show databases


if you want to use it use:
use nameofthedatabase

Datagrid to excel using ASP.NET

Datagrid to excel using ASP.NET
===========================


Two things to be done:
1) Fetch data from datasource and bind to datagrid
2) Pass the datagrid to ExportToExcel function. The content type should be application/vnd.ms-excel



//convert to excel from httpresponse
private void ExportToExcel(DataGrid dgExport, HttpResponse response )
{
response.Clear();
response.Charset = "";
response.ContentType ="application/vnd.ms-excel";

System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.Html32TextWriter htmlWrite = new System.Web.UI.Html32TextWriter(stringWrite) ;

DataGrid dg=new DataGrid();
dg=dgExport;

dg.GridLines =GridLines.None;
dg.HeaderStyle.Font.Bold =true;
dg.HeaderStyle.ForeColor =System.Drawing.Color.Red;
dg.ItemStyle.ForeColor =System.Drawing.Color.Black;


dg.DataBind();
dg.RenderControl(htmlWrite);
response.Write(stringWrite.ToString());
response.End();

}

//fetch date from datasource and bind to grid

private void cmdMakeExcel_Click(object sender, System.EventArgs e)
{
try
{
string strSQL = txtQuery.Text.ToString();
SqlDataAdapter daa = new SqlDataAdapter(strSQL, Connection.getConn());


DataSet Dsss = new DataSet();

daa.Fill(Dsss);
daa.FillSchema(Dsss,SchemaType.Mapped);
DataGrid Dss=new DataGrid();

Dss.DataSource = Dsss;
Dss.DataBind();

ExportToExcel(Dss,Response);
}
catch
{
Response.Write("Could Not Process");
}
}

console based input in C#

console based input in C#
====================


string userName;

Console.WriteLine ("Please Enter your name : ");
userName= Console.ReadLine();
Console.WriteLine ("Welcome {0} ",userName);



Please find that Console.ReadLine() is something like scanf in C language

PREFIX TO INFIX in C

PREFIX TO INFIX in C

#include<stdio.h>
struct stack
{
char data[7][16];
int tos;
}s;


main()
{
char prefix[20];
clrscr();
printf("PLEASE ENTER THE PREFIX EXPRESSION:");
scanf("%s",prefix);
preinf(prefix);
getch();
}

preinf(char prefix[])
{
int length,i,len;
char str1[20];
length=strlen(prefix);
for(i=length;i>=0;i--)
{
switch(prefix[i])
{
case '+':
case '-':
case '*':
case '/':
case '^':
{
str1[0]='(';
str1[1]='\0';
strcat(str1,pop());
len=strlen(str1);
str1[len]=prefix[i];
str1[++len]='\0';
strcat(str1,pop());
len=strlen(str1);
str1[len]=')';
str1[++len]='\0';
push(str1);
break;
}
default:
{
str1[0]=prefix[i];
str1[1]='\0';
push(str1);
}
}
}
printf("\nTHE INFIX EXPRESSION IS:%s",pop());
}

push(char string[])
{
strcpy(s.data[s.tos],string);
s.tos++;
}

pop()
{
s.tos--;
return(s.data[s.tos]);
}

PROGRAMME TO CONVERT INFIX EXPRESSION TO POSTFIX

/* PROGRAMME TO CONVERT INFIX EXPRESSION TO POSTFIX
EXPRESSION */


#include<stdio.h>
# define size 20
struct stk
{
char ele[size];
int tos;
};
typedef struct stk stack;
stack s;
main()
{
int len;
char infix[20],ch;
clrscr();
printf("PLEASE ENTER INFIX EMPRESSION:");
scanf("%s",infix);
len=strlen(infix);
infix[len]=')';
infix[++len]='\0';
printf("\n THE POSTFIX EXPRESSION IS:");
infpre(infix);
getch();
}

infpre(char infix[20])
{
int length,i,a,b;
char ch;
s.tos=0;
s.ele[s.tos]='(';
length=strlen(infix);
for(i=0;i<length;i++)
{
switch(infix[i])
{
case '*':
case '+':
case '-':
case '/':
case '^':
case '(':
case '$':
{
a=isp(s.ele[s.tos]);
b=icp(infix[i]);
if(a>=b)
{
ch=pop();
printf("%c",ch);
s.tos++;
push(infix[i]);
}
else
{
s.tos++;
push(infix[i]);

}
break;
}
case ')':
{
ch=pop();
while(ch!='(')
{
printf("%c",ch);
ch=pop();
}
break;
}
default:
printf("%c",infix[i]);
}}}

push(char ch)
{
s.ele[s.tos]=ch;
}

pop()
{
char ch;
ch=s.ele[s.tos];
s.tos--;
return(ch);
}

int isp(char a)
{
switch(a)
{
case '^':return(3);
case '*':
case '/':return(2);
case '+':
case '-':return(1);
case '(':return(0);
case '$':return(5);
}}

int icp(char a)
{
switch(a)
{
case '^':return(4);
case '*':
case '/':return(2);
case '+':
case '-':return(1);
case ')':return(4);
case '$':return(5);
}}

PREFIX TO POSTFIX in C

/* PREFIX TO POSTFIX in C*/

#include<stdio.h>
#include<string.h>
#define size 10
char ch;
struct stk
{
char ele[size];
int top;
}s;
main()
{
int length;
char infix[20];
clrscr();
printf("PLEASE ENTER THE PREFIX EXPRESSION:");
scanf("%s",infix);
length=strlen(infix);
infix[length]=')';
infix[++length]='\0';
printf("\nTHE POSTFIX MESSAGE IS:");
infpost(infix);
getch();
}
infpost(char infix[])
{
int a,b,length,i,count=0;
s.top=0;
s.ele[s.top]='(';
s.top++;
length=strlen(infix);
for(i=0;i<length;i++)
{
switch(infix[i])
{
case '*':
case '^':
case '/':
case '+':
case '-':
case '(':
{
a=isp(s.ele[s.top]);
b=icp(infix[i]);
/*printf("\nisp=%d icp=%d",a,b);
getch();*/
if(a>=b)
{
ch=pop();
printf("%c",ch);
s.top++;
push(infix[i]);
if(i==10)
break;
if(s.top==2)
{
s.top--;
ch=pop();
printf("%c",ch);
s.ele[1]=s.ele[2];
s.top=1;
}
}
else
{
if(count!=0) s.top++;
push(infix[i]);
count++;
break;
}}
case ')':
{
ch=pop();
while(ch!='(')
{
printf("%c",ch);
ch=pop();
}
break;
}
default:
printf("%c",infix[i]);
} } }


int push(char ch)
{
if(s.top==size-1)
{
printf("stack full \n");
return(0);
}
s.ele[s.top]=ch;
return(1);
}
int pop()
{
if(s.ele[s.top]==-1)
{
printf("stack empty");
return(0);
}
ch=s.ele[s.top];
s.top--;
return(ch);
}
int isp(char a)
{
switch(a)
{
case '^': return(3);
case '*':
case '/': return(2);
case '+':
case '-':return(1);
case '(':return(0);
}
}

int icp(char a)
{
switch(a)
{
case '^': return(4);
case '*':
case '/': return(2);
case '+':
case '-':return(1);
case ')':return(4);
}
}

PROGRAMME TO CONVERT INFIX TO PREFIX

/* PROGRAMME TO CONVERT INFIX TO PREFIX */


#include<stdio.h>
# define size 20
struct stk
{
char ele[size];
int tos;
};
typedef struct stk stack;
stack s;
main()
{
int len;
char infix[20],ch;
clrscr();
printf("PLEASE ENTER INFIX EMPRESSION:");
scanf("%s",infix);
len=strlen(infix);
infix[len]=')';
infix[++len]='\0';
printf("\n THE PREFIX EXPRESSION IS:");
infpre(infix);
getch();
}

infpre(char infix[20])
{
int length,i,a,b,len;
char ch,prefix[20],temp[20];
prefix[0]='\0';
s.tos=0;
s.ele[s.tos]='(';
length=strlen(infix);
for(i=0;i<length;i++)
{
switch(infix[i])
{
case '*':
case '+':
case '-':
case '/':
case '^':
case '(':
{
a=isp(s.ele[s.tos]);
b=icp(infix[i]);
if(a>=b)
{
ch=pop();
temp[0]=ch;
temp[1]='\0';
strcat(temp,prefix);
strcpy(prefix,temp);
s.tos++;
push(infix[i]);
}
else
{
s.tos++;
push(infix[i]);
}
break;
}
case ')':
{
ch=pop();
while(ch!='(')
{
temp[0]=ch;
temp[1]='\0';
strcat(temp,prefix);
strcpy(prefix,temp);
ch=pop();
}
break;
}
default:
{
len=strlen(prefix);
prefix[len]=infix[i];
prefix[++len]='\0';
}
}}
printf("%s",temp);
}

push(char ch)
{
s.ele[s.tos]=ch;
}

pop()
{
char ch;
ch=s.ele[s.tos];
s.tos--;
return(ch);
}

int isp(char a)
{
switch(a)
{
case '^':return(3);
case '*':
case '/':return(2);
case '+':
case '-':return(1);
case '(':return(0);
}}

int icp(char a)
{
switch(a)
{
case '^':return(4);
case '*':
case '/':return(2);
case '+':
case '-':return(1);
case ')':return(4);
}}

FORMING A TREE USING PREFIX EXPRESSION

/* FORMING A TREE USING PREFIX EXPRESSION AND THEN PREFORM
ALL THE TRAVERSALS(RECURSIVE) */


#include<stdio.h>
#include<ctype.h>
struct tree
{
char data;
struct tree *left,*right;
};
typedef struct tree btree;
char prefix[20];
btree *stack[20];
int top;
main()
{
btree *create(void);
void inorder(btree *temp);
void preorder(btree *temp);
void postorder(btree *temp);
void push(btree *temp);
btree *pop(void);
btree *root;
clrscr();
printf("PLEASE ENTER THE PREFIX EXPRESSION:");
gets(prefix);
root=create();
printf("\nTHE INORDER TRAVERSAL IS:");
inorder(root);
printf("\nTHE PREORDER TRAVERSAL IS:");
preorder(root);
printf("\nTHE POSTORDER TRAVERSAL IS:");
postorder(root);
getch();
}

btree *create(void)
{
btree *head,*temp,*temp1;
int i=0,n;
top=-1;
head=(btree*)malloc(sizeof(btree));
temp=head;
temp->data=prefix[i];
i++;
temp->right=temp->left=NULL;
push(temp);
n=strlen(prefix);
while(top!=-1)
{
while(!isalnum(prefix[i]))
{
temp=pop();
temp1=(btree*)malloc(sizeof(btree));
temp1->right=temp1->left=NULL;
temp->left=temp1;
temp1->data=prefix[i];
i++;
push(temp);
push(temp1);
}
temp1=(btree*)malloc(sizeof(btree));
temp=pop();
temp->left=temp1;
temp1->data=prefix[i];
temp1->left=temp1->right=NULL;
push(temp);
do {
temp=pop();
i++;
temp1=(btree*)malloc(sizeof(btree));
temp->right=temp1;
temp1->data=prefix[i];
temp1->right=temp1->left=NULL;
if(!isalpha(prefix[i]))
{i++;
push(temp1);
break;}
}while(top!=-1);
}
return(head);
}

void push(btree *temp)
{
top++;
stack[top]=temp;
return;
}
btree *pop(void)
{
return(stack[top--]);
}

void inorder(btree *temp)
{
if(temp)
{
inorder(temp->left);
putch(temp->data);
inorder(temp->right);
}
return;
}

void preorder(btree *temp)
{
if(temp)
{
putch(temp->data);
preorder(temp->left);
preorder(temp->right);
}
return;
}

void postorder(btree *temp)
{
if(temp)
{
postorder(temp->left);
postorder(temp->right);
putch(temp->data);
}
return;
}

PROGRAM TO SWAP TWO NUMBERS WITHOUT USING A THIRD VARIABLE IN C PROGRAMMING

PROGRAM TO SWAP TWO NUMBERS WITHOUT USING A THIRD VARIABLE IN C PROGRAMMING

This eveyone computer science student must have encountered.

void main()
{
int a,b;
printf("PLEASE ENTER THE TWO NUMBERS:");
scanf("%d %d",&a,&b);
/*little bit of maths*/
a=a+b;
b=a-b;
a=a-b;
printf("THE SWAPPED NUMBERS ARE:");
printf("%d %d",a,b);
getch();
}

Stack implementation using Array - c program (stack operation)

Stack implementation using Array - c program (stack operation)
===================================================


#include <stdio.h>
#include <conio.h>
#define size 10

int top = -1;
int stack[size];
int flag = 0;

void push (int *,int);
int pop (int *);
int peep (int *,int);
int update (int *,int);
void display (int *);

void main ()
{
int info,popped_element,position,data,pos_update,update_element,update_data;
char ch;

clrscr ();

do
{
printf("\n\ni<-Insert(push), d<-Delete(pop),p<-peep,u<-update, q<-Quit\n");
fflush (stdin);
printf("\n\nEnter your choice: ");
scanf("%c",&ch);
switch (ch)
{
case 'i':
{
printf("\n\nEnter the element you want to push: ");
scanf("%d",&info);
push (stack,info);
display (stack);
break;
}

case 'd':
{
popped_element = pop(stack);

if (flag == 0)
printf("\n\nThe element popped is %d",popped_element);
if (flag == 1)
printf("\nStack Underflow");
display (stack);
break;
}

case 'p':
{
printf("\n\nEnter the position of the stack from which you want to peep the element: ");
scanf("%d",&position);
data = peep(stack,position);
if (flag == 1)
printf("\nInvalid choice\n");
else
printf("The element peeped is %d",data);
display (stack);
break;
}

case 'u':
{
printf("Enter the position of the stack from which you want to update the data: ");
scanf("%d",&pos_update);
update_element = update(stack,pos_update);
if (flag == 1)
printf("Data can't be updated due to some reason");
else
printf("The data updated is %d",update_element);
display (stack);
break;
}

case 'q':
exit(0);
}
}while (ch != 'q');

getch ();
}

void push (int stack[],int info)
{
if (top == size-1)
printf("\nStack Overflow");
else
{
top++;
stack[top] = info;
}
}

int pop (int stack[])
{
int popped_element;
if (top == -1)
flag = 1;
else
{
flag = 0;
popped_element = stack[top];
top--;
}
return (popped_element);
}

void display (int stack[])
{
int i;
printf("\n\nThe contents of the stack are:\n");
for (i = top ; i >= 0 ; i--)
printf("%d ",stack[i]);
}

int peep (int stack[],int i)
{
int data;
if (top - i + 1 < 0)
flag = 1;
else
{
flag = 0;
data = stack[top-i+1];
}
return (data);
}

int update(int stack[],int pos)
{
int old_data;
if (top - pos + 1 < 0)
flag = 1;
else
{
flag = 0;
old_data = stack[top-pos+1];
printf("Enter the data you want to insert: ");
scanf("%d",&stack[top-pos+1]);
}
return (old_data);
}


Stack implementation using link list - c program
==============================

#include <stdio.h>
#include <conio.h>
struct Stack
{
int info;
struct Stack *next;
};
typedef struct Stack node;
node *first = NULL;
node *push (node *);
node *pop (node *);
void display (node *);

void main ()
{
char ch;

clrscr ();

do
{
fflush (stdin);
printf("\n\ni<-insert(push), d<-delete(pop), q<-quit\n");
printf("\n\nEnter the choice: ");
scanf("%c",&ch);
switch (ch)
{
case 'i':
{
first = push (first);
printf("\n\nAfter the push operation the stack is as follows:\n");
display (first);
break;
}

case 'd':
{
first = pop (first);
printf("\n\nAfter the pop operation the stack is as follows:\n");
display (first);
break;
}

case 'q':
exit (0);
}
}while (ch != 'q');

getch ();
}

node *push(node *first)
{
node *data;
data = (node *)malloc(sizeof(node));
printf("\nEnter the data to be inserted: ");
scanf("%d",&data->info);
data->next = first;
first = data;
return (first);
}

node *pop (node *first)
{
node *temp;
if (first == NULL)
printf("\n\nSTACK IS EMPTY\n");
else
{
temp = (node *)malloc(sizeof(node));
temp = first;
first = first->next;
printf("\nThe element deleted is %d",temp->info);
free (temp);
}
return (first);
}

void display (node *first)
{
while (first != NULL)
{
printf("%d ",first->info);
first = first->next;
}
}

PROGRAMME TO ENTER GRAPHICS MODE AND PRINT SOMETHING

PROGRAMME TO ENTER GRAPHICS MODE AND PRINT SOMETHING

#include<stdio.h>
#include<graphics.h>
main()
{
int ga=DETECT,gm;
initgraph(&ga,&gm," ");
settextstyle(0,0,100);
outtextxy(70,150,"PRAGATI PRAKASHAN");
getch();
closegraph();
}

PROGRAMME TO REVERSE A DOUBLY LINKED LINK LIST

/* PROGRAMME TO REVERSE A DOUBLY LINKED LINK LIST */


#include<stdio.h>
struct llist
{
int val;
struct llist *next,*prev;
};
typedef struct llist list;

main()
{
list *create(void);
void reverse(list *temp);
list *root;
clrscr();
printf("PLEASE ENTER THE LIST,ENTER -99 TO END:");
root=create();
reverse(root);
getch();
}

list *create(void)
{
list *head,*temp,*temp1;
int data;
head=(list*)malloc(sizeof(list));
temp=head;
head->prev=NULL;
do
{
scanf("%d",&data);
if(data==-99)
return(head);
temp1=(list*)malloc(sizeof(list));
temp1->val=data;
temp->next=temp1;
temp1->prev=temp;
temp1->next=NULL;
temp=temp1;
}while(1);
}

void reverse(list *head)
{
list *t1,*t2,*t3;
t1=head->next;
t2=t1->next;
t3=head;
do
{
t1->next=t3;
t1->prev=NULL;
head->next=t2;
t3->prev=t1;
t3=t1;
t1=t2;
t2=t2->next;
}while(t1!=NULL);
printf("\nTHE REVERSED LIST IS:");
t1=t3;
while(t1!=head)
{
printf(" %d",t1->val);
t1=t1->next;
}
return;
}

Link list programs in C (single, doubly and circular link list)

Link list programs in C (single, doubly and circular link list)
--------------------------------------------------------------------------------------



Singly link list
=================


#include <stdio.h>
#include <malloc.h>
#include <conio.h>

struct list
{
int info;
struct list *next;
};
typedef struct list node;

void main ()
{
node *first;
int choice;
node *create (node *);
node *insert (node *);
node *del (node *);
void display (node *);

clrscr ();

while (1)
{
printf("\n\nYou have following choices:\n");
printf("1. Create List\n");
printf("2. Insert a node in the List\n");
printf("3. Delete a node from the List\n");
printf("4. Display the List\n");
printf("5. Termenate the Program\n");
printf("Enter your choice: ");
scanf ("%d",&choice);
switch (choice)
{
case 1:
first = create(first);
break;
case 2:
first = insert (first);
break;
case 3:
first = del (first);
break;
case 4:
display (first);
break;
case 5:
exit (0);
}
}
}

node *create (node *first)
{
node *new1 = NULL,*l;
int i;
first = NULL;
printf("\n\nTHE INPUT IS:\n");
printf("-------------\n\n");
while(1)
{
printf("\nEnter -1 to break.....\n");
printf("Enter the node you want to enter in ascending order: ");
scanf("%d",&i);

if (i == -1)
break;

else
{
new1 = ((node *) malloc (sizeof (node)));
new1 -> info = i;
if(first == NULL)
{
first = l = new1;
}
else
{
l -> next = new1;
l = new1;
}
l -> next = NULL;
}
}
return (first);
}

void display (node *first)
{
printf("\n\nTHE OUTPUT IS:\n");
printf("--------------\n\n");
while (first != NULL)
{
printf("%d -> ",first -> info);
first = first -> next;
}
printf("NULL");
}

node *insert (node *first)
{
node *l, *new1;
l = first;
new1 = (node *) malloc (sizeof (node *));
printf("Enter the node: ");
scanf("%d",&new1 -> info);
if (first == NULL)
{
first = new1;
first -> next = NULL;
}
else
{
if (new1 -> info < first -> info)
{
new1 -> next = first;
first = new1;
}
else
{
while (l -> next -> info < new1 -> info && l -> next != NULL)
l = l -> next;
new1 -> next = l -> next;
l -> next = new1;
l = new1;
}
}
display (first);
return (first);
}

node *del (node *first)
{
int n;
node *l = first, *new1, *temp;
printf("Enter the information: ");
scanf("%d",&n);
if (first == NULL)
printf("\nLIST IS EMPTY\n");
else
{
if (first -> info == n)
{
temp = first;
first = first -> next;
free (temp);
}
else
{
while (l -> next -> info != n && l -> next != NULL)
l = l -> next;
if (l -> next == NULL)
printf("\nINFORMATION IS NOT PRESENT\n");
else
{
temp = l -> next;
l -> next = l -> next -> next;
free(temp);
}
}
}
display (first);
return (first);
}

Doubly Link List
===============

#include <stdio.h>
#include <alloc.h>
#include <conio.h>

struct Double
{
int info;
struct Double *next;
struct Double *previous;
};
typedef struct Double node;

node *create(node *);
node *insert(node *);
node *del(node *);
void display (node *);

node *first = NULL;

void main ()
{
int choice;

clrscr ();

while (1)
{
printf("\n\nYou have following choices:\n");
printf("1. Create List\n");
printf("2. Insert a node in the List\n");
printf("3. Delete a node from the List\n");
printf("4. Display the List\n");
printf("5. Termenate the Program\n");
printf("Enter your choice: ");
scanf ("%d",&choice);
switch (choice)
{
case 1:
first = create(first);
break;
case 2:
first = insert (first);
break;
case 3:
first = del (first);
break;
case 4:
display (first);
break;
case 5:
exit (0);
}
}
}

node *create (node *first)
{
node *new1,*l = NULL;
int i;
//first -> next = first -> previous = NULL;
while (1)
{
printf("Enter the information(-1 to Exit): ");
scanf("%d",&i);
if (i == -1)
break;
new1 = (node *)malloc(sizeof(node));
new1 -> info = i;
if (first == NULL)
{
first = l = new1;
first -> next = first -> previous = NULL;
}
else
{
new1 -> previous = l;
l -> next = new1;
l = new1;
}
l -> next = NULL;
}
return (first);
}

void display (node *first)
{
node *l;
l = first;
printf("\n\n\t\tDOUBLY LINK LIST:\n");
printf("\t\t-----------------\n");
printf("NULL");
for (l = first ; l != NULL ; l = l -> next)
printf(" <- %d -> ",l -> info);
printf("NULL");
}

node *insert (node *first)
{
node *new1,*l=NULL;
new1 = (node *)malloc(sizeof(node));
printf("\n\nEnter the node you want to insert: ");
scanf("%d",&new1->info);
if (first == NULL)
{
printf("Empty list. New list will be created.");
first = new1;
first->next = NULL;
first->previous = NULL;
}
else
{
if (new1->info < first->info)
{
new1->next = first;
new1->previous = NULL;
first->previous = new1;
first = new1;
}
else
{
l = first;
while (l->next->info < new1->info && l->next != NULL)
l = l->next;
new1->next = l->next;
l->next = new1;
new1->previous = l;
l = new1;
}
}
display (first);
return (first);
}

node *del (node *first)
{
int del_info;
node *l=NULL,*temp;
printf("\n\nEnter the information to be deleted: ");
scanf("%d",&del_info);
if (first == NULL)
printf("The List is Empty.");
else
{
if (first->info == del_info)
{
temp = first;
first = first->next;
first->previous = NULL;
free(temp);
}
else
{
l = first;
while (l->info < del_info && l->next != NULL)
l = l->next;
l->previous->next = l->next;
l->next->previous = l->previous;
}
}
display (first);
return (first);
}

Circular link list
=================


#include <stdio.h>
#include <malloc.h>
#include <conio.h>

///////////////////////STRUCTURE DEFINITION////////////////////////////////
struct cir_link_list
{
int info;
struct cir_link_list *next;
};
typedef struct cir_link_list node;

///////////////////////VARIABLE DECLARATION////////////////////////////////
node *first=NULL;
int info;

///////////////////////FUNCTION DECLARATION////////////////////////////////
node *create (node *);
void display (node *);
node *insert (node *);
node *del (node *);
int count = 0;

///////////////////////VOID MAIN () DEFINITION/////////////////////////////
void main ()
{
int choice;

clrscr ();

while (1)
{
printf("\n\nYou have following choices:\n");
printf("1. Create List\n");
printf("2. Insert a node in the List\n");
printf("3. Delete a node from the List\n");
printf("4. Display the List\n");
printf("5. Termenate the Program\n");
printf("Enter your choice: ");
scanf ("%d",&choice);
switch (choice)
{
case 1:
first = create(first);
break;
case 2:
first = insert (first);
break;
case 3:
first = del (first);
break;
case 4:
display (first);
break;
case 5:
exit (0);
}
}
}

///////////////////////CREATION OF CIRCULAR LINK LIST//////////////////////
node *create (node *first)
{
int i;
node *new1,*l=NULL;

while (1)
{
printf("Enter -1 to break........\n");
printf("Enter the node: ");
scanf("%d",&i);
if (i == -1)
{
l->next=first;
break;
}
else
{
new1 = ((node *)malloc(sizeof(node)));
new1 -> info = i;
if (first == NULL)
{
first = l = new1;
}
else
{
l->next=new1;
l=new1;
}
}
count++;
}
return (first);
}

///////////////////////DISPLAY OF CIRCULAR LINK LIST///////////////////////
void display (node *first)
{
int i;
for (i=0 ; i< count ; i++)
{
printf("%d -> ",first->info);
first = first -> next;
}
}

node *insert (node *first)
{
int i = 0;
node *l, *new1;
l = first;
new1 = (node *) malloc (sizeof (node *));
printf("\nEnter the node: ");
scanf("%d",&new1 -> info);
if (first == NULL)
{
first = new1;
first -> next = first;
}
else
{
if (new1 -> info < first -> info)
{
new1 -> next = first;
first = new1;
}
else
{
while (l -> next -> info < new1 -> info && l -> next != first && i <= count)
{
l = l -> next;
i++;
}
if (l -> next == first i > count)
{
new1 -> next = l -> next;
l -> next = new1;
l = new1;
}
new1 -> next = l -> next;
l -> next = new1;
}
}
count++;
display (first);
return (first);
}

node *del (node *first)
{
int n,i=0;
node *l = first, *new1, *temp;
printf("\nEnter the information: ");
scanf("%d",&n);
if (first == NULL)
printf("\nLIST IS EMPTY\n");
else
{
if (first -> info == n)
{
temp = first;
first = first -> next;
free (temp);
}
else
{
while (l -> next -> info != n && l -> next != first && i <= count)
{
l = l -> next;
i++;
}
if (l -> next == first i > count)
{
printf("\nINFORMATION IS NOT PRESENT\n");
goto jmp;
}
else
{
temp = l -> next;
l -> next = l -> next -> next;
free(temp);
}
}
}
count --;
jmp:
display (first);
return (first);
}

insert and delete queue in C++ (queue operation)

insert and delete queue in C++ (queue operation)
=======================================


# include<iostream.h>
# include<conio.h>
# include<string.h>
# include<ctype.h>
# include<process.h>
# define size 10
class Queue
{
public: int rear, front;
int ch;
int q[size];

public: Queue()
{
rear = front = 0;
}
void Insert_queue();
void Delete_queue();
void Display_queue();

};

// Function to create queue
void Queue :: Insert_queue()
{
cout<<"\n Input the element :";
cin>>ch;
if(rear < size)
{
rear ++;
q[rear] = ch ;
if(front == 0)
front = 1;
}
else
cout<<"\nOverflow";
}

// Function to perform delete operation
void Queue :: Delete_queue() //char q[], char ch)
{
if (front == 0)
{
cout<<"\nUnderflow";
return ;
}
else
{
ch = q[front];
cout<<"\nElement deleted :"<<ch;
}
if(front == rear)
{
front = 0;
rear = 0;
}
else
front = front + 1;
}

// Output function
void Queue :: Display_queue() //char q[])
{
if (front == 0)
return;
for( int i = front ; i <= rear; i++)
cout<<" "<<q[i];
}

//Function main
void main()
{
Queue Q;
int k = 0;
char choice;

do
{
cout<<"\nInsert->i Delete->d Quit->q:";
cout<<"\nInput the choice : ";
do
{
cin>>choice;
choice = tolower(choice);
}
while(strchr("idq",choice)==NULL);
cout<<"Your choice is ->"<<choice;
switch(choice)
{
case 'i' :
Q.Insert_queue();
cout<<"\nQueue after inserting ";
Q.Display_queue();
break;

case 'd' :
Q.Delete_queue();
cout<<"\nQueue content after deleteion is as follows:\n";
Q.Display_queue();
break;
case 'q':
k = 1;
}
}
while(!k);
}

Demonstrate use of mouse in C (assembly)

Demonstrate use of mouse in C (assembly)

/* PROGRAMME TO DEMONSTRATE USE OF MOUSE IN C LANGUAGE */
/* FORMING OUR OWN CURSOR */

#include<stdio.h>
#include<graphics.h>
#include<dos.h>
union REGS inregs;
struct SREGS sinregs;
static int mask[]={
0xe1ff,
0xe1ff,
0xe1ff,
0xe1ff,
0xe1ff,
0xe000,
0xe000,
0xe000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x1e00,
0x1200,
0x1200,
0x1200,
0x13ff,
0x1249,
0x1249,
0xf249,
0x9001,
0x9001,
0x9001,
0x8001,
0x8001,
0x8001,
0xffff
};
main()
{
int gd=DETECT,gm;
initgraph(&gd,&gm,"");
cleardevice();
inregs.x.ax=0;
int86(0x33,&inregs,&inregs);
inregs.x.ax=1;
int86(0x33,&inregs,&inregs);
inregs.x.ax=9;
inregs.x.bx=5;
inregs.x.cx=0;
inregs.x.dx=(int)mask;
segread(&sinregs);
sinregs.es=sinregs.ds;
int86x(0x33,&inregs,&inregs,&sinregs);
getch();
closegraph();
}