Jump to content



Recent Topics

Recent Status Updates

View All Updates

Most Liked Content


#420758 Creating login/registration forms with PHP

Posted by amrosama on 31 December 2008 - 07:39 AM

Creating Login/Registration Forms with PHP

This tutorial will help you as a beginner to create a simple login page for your php projects, in this tutorial you will learn about sessions in php, inserting and retrieving records from mysql server.
 

The database table:
Before writing the code create this table in your server by running the text file attached with mysql console or simply create it yourself, we will use it to store the users information

CREATE TABLE `test`.`users` (
`id` INT NOT NULL auto_increment ,
`name` VARCHAR( 20 ) NOT NULL ,
`password` VARCHAR( 20 ) NOT NULL ,
`email` VARCHAR( 20 ) NOT NULL ,
PRIMARY KEY ( `id` )
)

Let’s start:
A.The login page(main page):
In this simple php page there are three session variables we are using; “logging”, “logged”, and “user” they are all bool variables. We will use them to execute the right code for each scenario

 

 

<html>
<head>
<title>login page</title>
</head>
<body bgcolor="black" style="color:gray">
<form action="index.php" method=get>
<h1 align="center" style="color:gray" >Welcome to this simple application</h1>
<?php
session_start();
if($_SESSION["logged"])
{
print_secure_content();
}
else {
if(!$_SESSION["logging"])
{
$_SESSION["logging"]=true;
loginform();
}
else if($_SESSION["logging"])
{
$number_of_rows=checkpass();
if($number_of_rows==1)
{
$_SESSION[user]=$_GET[userlogin];
$_SESSION[logged]=true;
print"<h1>you have loged in successfully</h1>";
print_secure_content();
}
else{
print "wrong pawssword or username, please try again";
loginform();
}
}
}

1-the first thing to do when you are using session variables on a php page is to start the session service on the page by this line “session_start();”, if you ignored this line the page will work fine but the session variables wont be saved when you refresh the page or go to another page.

2-after starting the service, we check if the user is already logged in “if($_SESSION['logged'])“, if he is we print him a nice welcome message by calling the function for the secure content (we will look at it later)

3-if he isn’t logged in, we show the login fields (username and password) by the function “loginform()”, and set the session variable” $_SESSION["logging"]” to true in order to check the entered username and password when he/or she hits the login button

4-when he/or she enters the username and password then hits the login in button the code that will be only executed will be the code after “else if($_SESSION["logging"])“ because we have set the logging session variable to true, in this code block the variable “$number_of_rows” gets its value from the function “checkpass()” which is basically takes the username and password and checks the server if it already exists, if it exists it returns one else it will return 0…..thats why we check “$number_of_rows”:
- if it equals one if it really does we will set the variable “user” in the session to the entered username, and sets the logged bool variable to true.
--If the “$number_of_rows” isn’t 1, we will print him the input fields again.

Now let’s look at the functions:
1.loginform()
 

 

function loginform()
{
print "please enter your login information to proceed with our site";
print ("<table border='2'><tr><td>username</td><td><input type='text' name='userlogin' size'20'></td></tr><tr><td>password</td><td><input type='password' name='password' size'20'></td></tr></table>");
print "<input type='submit' >";
print "<h3><a href='registerform.php'>register now!</a></h3>";
}
 

 


all it does is printing out the fields to the user

2.checkpass()
 

 

function checkpass()
{
$servername="localhost";
$username="root";
$conn= mysql_connect($servername,$username)or die(mysql_error());
mysql_select_db("test",$conn);
$sql="select * from users where name='$_GET[userlogin]' and password='$_GET[password]'";
$result=mysql_query($sql,$conn) or die(mysql_error());
return mysql_num_rows($result);
}
 

 


This function establishes a connection with the mysql server through the “mysql_connect()” function which takes in two parametes;1.servername (or address) 2.the username used to login to the database, if theres a password you should add it
After connection to the server we choose the database that we will use using the “mysql_select_db();” function which takes in 2 variables;1. The name of the database and 2.The connection variable.
The sql statement:
 

 

$sql="select * from users where name='$_GET[userlogin]' and password='$_GET[password]'";
 

 


It simple gets the field that match the user login and password that the user have entered along with the ones in in the table called “users”, after that we run the statement using the function “mysql_query($sql,$conn)” and returning the results to a variable called $result
Finally we return the number of retrieved rows.

3.print_secure_content()
 

 

function print_secure_content()
{
print("<b><h1>hi mr.$_SESSION[user]</h1>");
print "<br><h2>only a logged in user can see this</h2><br><a>href='logout.php'>Logout</a><br>";

}
 

 


No explanation needed

B. The logout page:
If the user wishes to logout, we clear the session variables this can be easily done by making him open this php page “logout.php”
 

 

<?php
session_start();
if(session_destroy())
{
print"<h2>you have logged out successfully</h2>";
print "<h3><a href='index.php'>back to main page</a></h3>";
}
?>
 

 


What we did here is starting the session and destroying it, if it was cleared successfully we display that to the user

c. Registration form:
A simple html page that lets the use enters the name and passwords and submit it to the serve on the page “register.php”
 

 

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>register</title>
</head>
<body bgcolor="black" style="color:white;">
<FORM ACTION="register.php" METHOD=get>
<h1>welcome to the registration page</h1>
please input the registration details to create an account here<br>
<table border="2">
<tr>
<td>User Name :</td><td><input name="regname" type="text" size"20"></input></td>
</tr>
<tr>
<td>email :</td><td><input name="regemail" type="text" size"20"></input></td>
</tr>
<tr>
<td>password :</td><td><input name="regpass1" type="password" size"20"></input></td>
</tr>
<tr>
<td>retype password :</td><td><input name="regpass2" type="password" size"20"></input></td>
</tr>
</table>
<input type="submit" value="register me!"></input>
</FORM>
</body>
</html>
 

 


Note: you can add some JavaScript to validate the code before submitting, but I didn’t want to make this tutorial long and boring

d. register php page:
This PHP script checks the data that the user have entered in the “registrationfor.php” and inserts it into the database (simple, huh?).
 

 

<?php
if($_GET["regname"] && $_GET["regemail"] && $_GET["regpass1"] && $_GET["regpass2"] )
{
if($_GET["regpass1"]==$_GET["regpass2"])
{
$servername="localhost";
$username="root";
$conn= mysql_connect($servername,$username)or die(mysql_error());
mysql_select_db("test",$conn);
$sql="insert into users (name,email,password)values('$_GET[regname]','$_GET[regemail]','$_GET[regpass1]')";
$result=mysql_query($sql,$conn) or die(mysql_error());
print "<h1>you have registered sucessfully</h1>";

print "<a href='index.php'>go to login page</a>";
}
else print "passwords doesnt match";
}
else print"invaild data";
?>

 

 


The first line checks if all the variables in the get isn’t null then it checks if the two password fields match, if yes it connects to the server, selects the database and runs the sql insert statement, which is:
 

 

$sql="insert into users (name,email,password)values('$_GET[regname]','$_GET[regemail]','$_GET[regpass1]')";
 

 


No explanation needed

Important Notes:
1.you can use this code to check the available variables and its values in your session or any other global variables
 

foreach ($_SESSION as $key=>$value) {
print "\$_ SESSION [\"$key\"] == $value<br>";}

 

 


2.its wise to check if a session variable exists before using it this can be done using this code:
 

 

if(isset($_SESSION['variable_name'])) print “it exists”;
else print “it doesn’t”;

 

 


3.you can hide the values of your form submits by using the POST method of your forms


That’s all, I hope that you find this tutorial helpful and don’t hesitate to ask or comment here.

All the files above are attached in this thread

 

Want to learn more? Below are a few more login and registration tutorials:

Creating A Simple Yet Secured Login/registration With Php5

Simple Login/Register/Main Script

PHP Login page!

 

To learn more about more complex projects, check out Building a Big Project Part 1 (in PHP).

Attached Images

  • successful login.JPG

Attached Files




#528865 Pointers: What, How, and Why

Posted by ZekeDragon on 01 December 2009 - 01:31 AM

If you are new to C or C++ programming, you may be perplexed by your first encounter with a pointer. What is it good for, how do I use them in my own programs, and what do they actually do? These things aren't always easy to understand, but this tutorial will shed some light on the subject.

What is a Pointer:
A pointer is just an address indicating to the program a location in memory. This location could point to anything, but thanks to C and C++'s strong typing you'll know what it points to when you're programming. You can think of a pointer like a signpost that tells your program where to look in RAM for the variable you're referring to, and you can think of addresses like a numbered list of home addresses going from 0 on up. The figure below is a pictographical representation showing this relationship between pointer and value.
Posted Image
As you can see, the pointer itself contains an address in memory, and that address in memory contains a value. You'll soon learn that a pointer can point to another pointer, and why you'd want to do that, but all you have to envision is taking the above picture to that next level of indirection, an address referring to another address, that finally refers to a value.

Using Pointers:
Since a pointer is just an address, you can use it to point to values in your programs. So how would you get the value the pointer is pointing to? The magic word here is "dereferencing", which tells the compiler you want the value the pointer is pointing to. This is easy to do, using the dereferencing operator (*). It's the same symbol for multiplication, but it's how it's used in context that matters. Below is a code snipped that dereferences a value and assigns it to an integer:
int myNumber = *otherNumber;
The syntax is quite simple, but it shows that pointers and non-pointers must be treated differently everywhere in your program. This includes some other different pointer syntaxes (including the arrow operator "->", but that's for later).

Arrays:
The easiest and most familiar use of pointers is when you learned about arrays, since an array is just a block of data pointed at by a pointer. Observe this simple C/C++ example below:
#include <stdio.h>

int main(void)
{
    /* myArray is just a pointer to five ints. */
    int myArray[] = { 1, 2, 3, 4, 5 };

    /* You can dereference myArray like a pointer, and get the first value */
    printf("%d", *myArray);

    return 0;
}
This shows that an array, just like a pointer, can be dereferenced to acquire it's first value. In fact, going through an array's contents is just the act of dereferencing, which tells the compiler you want the value the pointer is pointing to. There are several different syntax changes when using pointers, since pointer types must be treated differently from non-pointer types. Normally for arrays the above syntax is discouraged, but you should keep in mind that arrays are pointers, just pointing to statically declared memory. What this means is myArray[4] is the same as *(myArray + 4), but obviously the former is less confusing. Here's an image showing how pointers point to arrays in memory:
Posted Image

Strings:
A string is an array of characters in C. You can set a string easily like so:
char string[]="This is a string!";
And then you can print it like this:
printf("%s\n", string);
The pic above is actually an example of a string, showing the string "abc" in memory. Because every character is an element of the array, you can handle all of the characters separately in a string. The last character in a string is always a 0, that is the NULL character '\0'. If there is a NULL character in the middle of a string, you will only see the first part of the string up until the NULL character.
If you want to print the second character, it's as easy as this:
printf("%c\n", string[1]);
Just remember that array indices start at 0.

Passing pointers as parameters:
So now that you know what the asterisk is for, and one of the purposes of pointers is for arrays, how can you use this to help you? The second thing you can do with a pointer is, just like any other value, you can pass it as a parameter to another function. This, however, has the added benefit of making it so that function can now modify the contents of what was passed! To exemplify this, take a look at this example:
#include <stdio.h>

void changeToFive(int* change)
{
    *change = 5;
}

int main(void)
{
    int anum = 3;
    int* pointy;

    printf("anum = %d", anum);
    pointy = &anum;
    changeToFive(pointy);
    printf("anum now = %d", anum);

    return 0;
}

Address-Of:
You may have noticed this strange line in the above code:
pointy = &anum;
You can make pointers point to any variable you have already defined. To get the address of a variable, prefix it with the aptly named address-of operator (&). The above code assigns the address of anum to be pointed to by pointy.

The following code will assign a value of 54 to number, and have pointer point to number. It then prints the value of number by dereferencing it, and it prints the address that pointer points to.
#include <stdio.h>

int main(void)
{
    int number=54;
    int *pointer;

    pointer=&number;
    printf("pointer's address value is %p, and the value at that address is %d", pointer, *pointer);

    return 0;
}

Passing arrays as parameters:
Now that you know how to pass a pointer, and how to dereference arrays using the [] operators, you've almost got the basics of pointers! There's just one more thing to bring up, and it's how to pass an array itself as a parameter. Since you already know that an array is just a pointer, passing an array is identical to passing a pointer, except your receiving function treats it like an array.
#include <stdio.h>

void makeAllLetterX(char* array)
{
    for (int iii = 0; array[iii] != '\0'; ++iii)
    {
        array[iii] = 'X';
    }
}

int main(void)
{
    char string[] = "Hello Wordl!";

    printf("%s\n", string);
    makeAllLetterX(string);
    printf("%s\n", string);

    return 0;
}

Gotchas:
There are some problems with pointers that can make using them dangerous:
  • If you attempt to dereference a pointer without assigning it a value, this results in, according to the C standard, "Undefined behavior". Undefined behavior is the worst kind of behavior, since this essentially means your entire program becomes undefined, and thus buggy. This kind of pointer is also known as a "wild pointer".
  • Dereferencing a NULL pointer is equally dangerous, and according to the C99 standard, also leads to undefined behavior.
  • Obviously due to the above, passing a NULL pointer to a function that doesn't specifically document accepting NULL pointers or passing a wild pointer to any function is equally dangerous.

Other purposes:
Oh, and there's one more purpose behind pointers... perhaps the best reason for them at all, the reason some languages ONLY use pointers, the reason the languages designers put it there in the first place... dynamic memory allocation! C and C++ treat this field differently, but nonetheless both make use of pointers for dynamic memory. If you want to read more about that, there is a tutorial for C here.

In C and C++, pointers are a very important and useful part of the language. Understand how pointers work, and you will go far in C and C++!

This collaborative tutorial was brought to you by ZekeDragon and Guest. Any suggestions, questions, and positive feedback is welcome. As always, +rep is appreciated, just remember to give us both credit.


#528199 Reading Command Line Arguments

Posted by Guest on 27 November 2009 - 03:43 PM

This is a simple tutorial that will show you how to read command line arguments and how to parse them with getopt.

To read command line arguments, you must declare main in a special way.
Here is how you declare main:
int main(int argc, char **argv)
Their are two variables, argc and argv. argc stands for argument count, so it is how many arguments are passed on the command line. argv is a pointer to a pointer, it is the set of actual arguments. This may seem confusing at first.

About argv:
A string is a pointer to a bunch of characters, right? Well argv is a pointer to a bunch of strings. For example, argv[0] is a pointer to the first argument, stored as a string.

Here is an example program that prints out all of the command line arguments you provide:
#include <stdio.h>

int main(int argc, char **argv)
{
	int i; //counter
	for (i=0;i<argc;i++)
		printf("%s\n", argv[i]);
	return 0;
}
Seems easy enough, right? Now that is only half of it. Most programs accept arguments using dashes, for example:
ls -a
In Unix would list the directory, and -a means list all files. To recognize and parse these options, programs use a function called getopt.
In order to use getopt, you must include this line:
#include <unistd.h>
Note: This file is part of the C POSIX library, and will not work on Windows unless compiled with Mingw or Cygwin.

Using getopt:
getopt is almost always used in a loop. When there are no more arguments to parse, getopt will return -1. You use getopt like this:
c=getopt(argc, argv, "abc");
argc and argv are the arguments from main. "abc" is the set of characters that are acceptable arguments. c is simply a character that is the argument returned by getopt.

Arguments that take options:
Some arguments need to take an option. For example, many programs use the argument "-f file" to provide file access. When arguments use options, you must follow the acceptable argument by a colon. For example, "a:bc" will accept arguments a, b, and c, and a will have an extra option. The extra option is stored in *optarg.

Here is an example program that can take two arguments, -a and -x. It will tell you if -a is provided, and if -x is provided. It will also tell you the option that -x is provided with.
#include <unistd.h>
#include <stdio.h>

int main (int argc, char **argv)
{
	int c;
	while ((c=getopt(argc, argv, "ax:")) != -1) {
		if(c=='a')
			printf("-a was provided\n");
		if(c=='x')
			printf("-x was provided with %s\n", optarg);
	}
	return 0;
}

There are actually more things you can do with getopt, but I will not cover those things here. Any feedback is welcome. Please post here if you have any questions, or improvements. +rep is appreciated a lot!


#507662 Upcasting, downcasting

Posted by Sinipull on 11 September 2009 - 07:35 AM

Upcasting and downcasting are important part of Java, which allow us to build complicated programs using simple syntax, and gives us great advantages, like Polymorphism or grouping different objects. Java permits an object of a subclass type to be treated as an object of any superclass type. This is called upcasting. Upcasting is done automatically, while downcasting must be manually done by the programmer, and i'm going to give my best to explain why is that so.

Upcasting and downcasting are NOT like casting primitives from one to other, and i believe that's what causes a lot of confusion, when programmer starts to learn casting objects.

Throughout this tutorial i'm going to use Animal hierarchy to explain how class hierarchy works.

Inheritance

updown.png

What we have here, is a simplified version of an Animal Hierarchy. You can see, that Cat and Dog are both Mammals, which extends from Animal, which silently extends from Object. By silently, i mean, that Java automatically extends every class from Object class, which isn't extended from something else, so everything is an Object (except primitives).

Now, if you ask - is Cat an Object - It doesn't extend Object, it extends Mammal?
By inheritance Cat gets all the properties its ancestors have. Object is Cat's grandgrandparent, which means Cat is also an Object. Cat is also an Animal and a Mammal, which logically means - if Mammals possess mammary glands and Animals are living beings, then Cat also has mammary glands and is living being.

 

Basic JTable and Netbeans


What this means for a programmer, is that we don't need to write for every possible Animal, that it has health. We just need to write it once, and every Animal gets it through inheritance.
Consider the following example:
 

class Animal {
int health = 100;
}

class Mammal extends Animal { }

class Cat extends Mammal { }

class Dog extends Mammal { }

public class Test {
public static void main(String[] args) {
Cat c = new Cat();
System.out.println(c.health);
Dog d = new Dog();
System.out.println(d.health);
}
}


When running the Test class, it will print "100" and "100" to the console, because both, Cat and Dog inherited the "health" from Animal class.

Upcasting and downcasting

First, you must understand, that by casting you are not actually changing the object itself, you are just labeling it differently.
For example, if you create a Cat and upcast it to Animal, then the object doesn't stop from being a Cat. It's still a Cat, but it's just treated as any other Animal and it's Cat properties are hidden until it's downcasted to a Cat again.
Let's look at object's code before and after upcasting:

Cat c = new Cat();
System.out.println(c);
Mammal m = c; // upcasting
System.out.println(m);

/*
This printed:
Cat@a90653
Cat@a90653
*/


As you can see, Cat is still exactly the same Cat after upcasting, it didn't change to a Mammal, it's just being labeled Mammal right now. This is allowed, because Cat is a Mammal.

Note that, even though they are both Mammals, Cat cannot be cast to a Dog. Following picture might make it a bit more clear.
updown2.png

Although there's no need to for programmer to upcast manually, it's allowed to do.
Consider the following example:
 

Mammal m = (Mammal)new Cat();


is equal to
 

Mammal m = new Cat();


But downcasting must always be done manually:
 

Cat c1 = new Cat();
Animal a = c1; //automatic upcasting to Animal
Cat c2 = (Cat) a; //manual downcasting back to a Cat


Why is that so, that upcasting is automatical, but downcasting must be manual? Well, you see, upcasting can never fail. But if you have a group of different Animals and want to downcast them all to a Cat, then there's a chance, that some of these Animals are actually Dogs, and process fails, by throwing ClassCastException.

 

Double buffering, movement, and collision detection


This is where is should introduce an useful feature called "instanceof", which tests if an object is instance of some Class.
Consider the following example:
 

Cat c1 = new Cat();
Animal a = c1; //upcasting to Animal
if(a instanceof Cat){ // testing if the Animal is a Cat
System.out.println("It's a Cat! Now i can safely downcast it to a Cat, without a fear of failure.");
Cat c2 = (Cat)a;
}


Note, that casting can't always be done in both ways. If you are creating a Mammal, by calling "new Mammal()", you a creating a Object that is a Mammal, but it cannot be downcasted to Dog or Cat, because it's neither of them.
For example:

Mammal m = new Mammal();
Cat c = (Cat)m;


Such code passes compiling, but throws "java.lang.ClassCastException: Mammal cannot be cast to Cat" exception during running, because im trying to cast a Mammal, which is not a Cat, to a Cat.

General idea behind casting, is that, which object is which. You should ask, is Cat a Mammal? Yes, it is - that means, it can be cast.
Is Mammal a Cat? No it isn't - it cannot be cast.
Is Cat a Dog? No, it cannot be cast.
Important: Do not confuse variables with instances here. Cat from Mammal Variable can be cast to a Cat, but Mammal from Mammal variable cannot be cast to a Cat.

 

Creating an Executable Jar File


Cats cant purr, while being labeled something else
If you upcast an object, it will lose all it's properties, which were inherited from below it's current position. For example, if you cast a Cat to an Animal, it will lose properties inherited from Mammal and Cat. Note, that data will not be lost, you just can't use it, until you downcast the object to the right level.
Why is it like that? If you have a group of Animals, then you can't be sure which ones can meow() and which ones can bark(). That is why you can't make Animal do things, that are only specific for Dogs or Cats.
updown7.png

However the problem above is not an obstacle, if you choose to use polymorphism. Polymorphism uses automatic downcast during method calls. I'm not going to go into details with this one, so i'm referring to Polymorphism tutorial by Turk4n: http://forum.codecal...lymorphism.html
updown5.png

Upcasting during method calling

The beauty of casting is that programmer can make general methods, which can take a lot of different classes as an argument.
For example:
 

public static void stroke(Animal a){
System.out.println("you stroke the "+a);
}


This method can have what ever Animal or it's subclass as an argument. For example calling:
 

Cat c = new Cat();
Dog d = new Dog();
stroke(c); // automatic upcast to an Animal
stroke(d); // automatic upcast to an Animal


..is a correct code.

updown3.png

however, if you have a Cat, that is currently being held by Animal variable, then this variable cannot be argument for a method, that expects only Cats, even though we currently have a instance of Cat - manual downcasting must be done before that.

updown4.png

About variables

Variables can hold instance of objects that are equal or are hierarchically below them. For example Cat c; can hold instances of Cat and anything that is extended from a Cat. Animal can hold Animal, Mammal, etc..
Remember, that instances will always be upcasted to the variable level.

"I really need to make a Dog out of my Cat!"

Well, you can't do it by casting. However, objects are nothing else, but few methods and fields. That means, you can make a new dog out of your Cat's data.

Let's say you have a Cat class:
 

class Cat extends Mammal {
Color furColor;
int numberOfLives;
int speed;
int balance;
int kittens = 0;

Cat(Color f, int n, int s, int B){
this.furColor = f;
this.numberOfLives = n;
this.speed = s;
this.balance = b;
}
}


and a Dog class.
 

class Dog extends Mammal {
Color furColor;
int speed;
int barkVolume;
int puppies = 0;

Dog(Color f, int n, int s, int B){
this.furColor = f;
this.speed = s;
this.barkVolume = b;
}
}


and you want to make a Dog out of the Cat. All you need to do, is, place a method inside of the Cat class, that converts the fields and returns a new Dog based on that.
 

public Dog toDog(int barkVolume){
Dog d = new Dog(furColor, speed, barkVolume);
d.puppies = kittens;
return d;
}


As you can see, they don't match that well, so some fields were inconvertible, and some data had to be made from scratch. Notice, that numberOfLives and Balance were not converted, and barkVolume was completely new data. If you have 2 Classes, that match perfectly, then hurray, but it rarely happens.
conversion can now be called from where ever you need:
 

Cat c = new Cat(Color.black, 9, 20, 40);
Dog d = c.toDog(50);


Thanks for reading.

 

Looking for some more related topics?

About casting/downcasting

Polymorphism help ..!!

Inherritance or Interfaces

 

 




#528868 Pointers: What, How, and Why

Posted by Guest on 01 December 2009 - 01:41 AM

I hope you like our collaborative tutorial! If you choose to +rep ZekeDragon, make sure you +rep me too!


#514690 Dynamic Arrays: Using malloc() and realloc()

Posted by Guest on 10 October 2009 - 11:41 AM

Note: This tutorial uses pointers pretty heavily. If don't understand pointers, please read this tutorial before you go on.

This has been bugging me for a little while, but I figured it out. I will share my knowledge to the rest of the world! If you need to take data from the user that could be any length, you could define a really big array like so:


int array[100000];

 

There are several problems with this. No matter how big the array is, the user could still have more input. If the user doesn't have that much input, you have wasted memory.

When you are using malloc(), realloc() and free() you need the following header file:


#include <stdlib.h>

 

First, I will show you how to allocate memory for a pointer. You can declare a pointer like so:


int *pointer;

 

Basics of while loop, char arrays in c and Tic Tac Toe using them

 

The pointer can point to any location at first. You should always make it point to something or you can allocate some memory that your pointer will point to. To do this, you need to use the malloc() function. Use it like so:

 

pointer=malloc(2*sizeof(int));

 

malloc() returns a void pointer and takes an argument of how many bytes to allocate. Because pointer points to an integer, we use the 2*sizeof(int). Using malloc like the above is similar to doing this:


int array[2];

 

Error checking:
If the operating system can't allocate more memory for your program, malloc will fail and return a NULL value. It's always a good idea to make sure malloc is successful:


pointer=malloc(1*sizeof(*pointer));
if (pointer==NULL) {
printf("Error allocating memory!\n"); //print an error message
return 1; //return with failure
}

 

Pointers: What, How, and Why

 

Now I will show you how to use realloc(). You use realloc after you have used malloc to give a pointer more or less memory. Let's say you want to give a pointer 5 integers of memory. The code should look like this:


int *temp = realloc(pointer, 5*sizeof(int));
if ( temp != NULL ) //realloc was successful
{
pointer = temp;
}
else //there was an error
{
free(pointer);
printf("Error allocating memory!\n");
return 1;
}

 

This is just like malloc, except realloc takes two arguments. The first argument is the pointer you want to copy the data from. The above code copies pointer to temp, then copies temp back to pointer if everything goes correctly. You may have noticed a new function though, and that is free().

 

Creating a Two Dimensional Vector

 

Free is used to free the memory you have allocated with malloc or realloc. All memory that you allocate should be freed when you are done using it. Free takes a pointer as an argument like so:


free(pointer);

 

Here is an example program that makes use of a dynamic array. Everything you need to know is in the comments.

 

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

/* This program takes input and outputs everything backwards */

int main()
{
int *data,*temp;
data=malloc(sizeof(int));
int c; /* c is the current character */
int i; /* i is the counter */
for (i=0;;i++) {
c=getchar(); /* put input character into c */
if (c==EOF) /* break from the loop on end of file */
break;
data[i]=c; /* put the character into the data array */
temp=realloc(data,(i+2)*sizeof(int)); /* give the pointer some memory */
if ( temp != NULL ) {
data=temp;
} else {
free(data);
printf("Error allocating memory!\n");
return 1;
}
}
/* Output data backwards one character at a time */
for (i--;i>=0;i--)
putchar(data[i]);
/* Free the pointer */
free(data);
/* Return success */
return 0;
}

 

So that's it. Any suggestions for improvement are welcome. +Reputation is very much appreciated.

 

Want to learn more about arrays?

Threads in Linux using c/c++ - Part 1

Pointers and Arrays in C

Problem: Printing a 2D array in spiral like shape

New Sorting - with order arrays

 




#434926 Game - A simple Pong

Posted by eard on 17 February 2009 - 05:55 PM

Hello guys, this is my first thread.
And i will show you how to make a simple Pong game. I say simple because i made it in less than 40 min.


First of all, like i'm Mexican, all my variables will be in Spanish, but i will write comments in English about what do each part of code.
Here we go

Points to consider
The Pong game that we are going to make in this tutorial will be for 2 players, P1 vs P2. The keys to move the player one will be 'W' and 'S', and for player two will be up arrow and down arrow.
Also, when a player reach to 6 points, the game will end. You can change this value if you want

 

How to make an economical main game loop (essential for big games)


First Step

We'll create the "container window". This class will just listen the keys pressed and released from the keyboard and send them to the game class, that will be created later. Also, in this class (Main) we'll create a new panel from the game class.
Create a new class and name it like do you prefer. I will call it Main.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Main extends JFrame {

private static final long serialVersionUID = 1L; // Eclipse added this automatically

private JPanel jContentPane = null;

private PanelPelota panel = null; // This is the panel of the game class

private PanelPelota getPanel() {
if (panel == null) {
panel = new PanelPelota(); // The panel is created
}
return panel;
}

/**
* This is the default constructor
*/
public Main() {
super();
initialize();
// Listeners for the keyboard
this.addKeyListener(new KeyAdapter() {
//Method for the key pressed
public void keyPressed(KeyEvent evt) {
formKeyPressed(evt);
}
// Method for the key released
public void keyReleased(KeyEvent evt) {
formKeyReleased(evt);
}
});

}

// Here i'm stating the method that will send the key pressed to the game class
private void formKeyPressed(KeyEvent evt)
{
panel.keyPressed(evt);
}

// Here i'm stating the method that will send the key released to the game class
private void formKeyReleased(KeyEvent evt)
{
panel.keyReleased(evt);
}

/**
* This method initializes this
*
* @return void
*/
private void initialize() {
this.setResizable(false);
this.setBounds(new Rectangle(312, 184, 250, 250)); // Position on the desktop
this.setMinimumSize(new Dimension(250, 250));
this.setMaximumSize(new Dimension(250, 250));
this.setContentPane(getJContentPane());
this.setTitle("Pong");
}

/**
* This method initializes jContentPane
*
* @return javax.swing.JPanel
*/
private JPanel getJContentPane() {
if (jContentPane == null) {
jContentPane = new JPanel();
jContentPane.setLayout(new BorderLayout());
jContentPane.add(getPanel(), BorderLayout.CENTER);
}
return jContentPane;
}

public static void main(String[] args) {
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Main thisClass = new Main();
thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
thisClass.setVisible(true);
}
});
}
}

 

 

How to create a text based web browser game


Second Step
Now that we have the container window, we will create the game class. In this class we are going to draw the ball and the "ships" of the players.
I'll create a bew class called PanelPelota, Pelota in English is Ball.

 

import java.awt.*;
import java.awt.event.KeyEvent;
import javax.swing.*;


public class PanelPelota extends JPanel implements Runnable {

private static final long serialVersionUID = 1L;
// Positions on X and Y for the ball, player 1 and player 2
private int pelotaX = 10, pelotaY = 100, jug1X=10, jug1Y=100, jug2X=230, jug2Y=100;
Thread hilo;
int derecha=5; // to the right
int izquierda= -5; //to the left
int arriba=5; // upward
int abajo= -5; // down
int ancho, alto; // Width and height of the ball
// Scores
int contPlay1=0, contPlay2=0;
boolean player1FlagArr,player1FlagAba, player2FlagArr, player2FlagAba;
boolean juego, gameOver;

public PanelPelota(){
juego=true;
hilo=new Thread(this);
hilo.start();
}

// Draw ball and ships
public void paintComponent(Graphics gc){
setOpaque(false);
super.paintComponent(gc);

// Draw ball
gc.setColor(Color.black);
gc.fillOval(pelotaX, pelotaY, 8,8);

// Draw ships
gc.fillRect(jug1X, jug1Y, 10, 25);
gc.fillRect(jug2X, jug2Y, 10, 25);

//Draw scores
gc.drawString("Jugador1: "+contPlay1, 25, 10);
gc.drawString("Jugador2: "+contPlay2, 150, 10);

if(gameOver)
gc.drawString("Game Over", 100, 125);
}

// Positions on X and Y for the ball
public void dibujarPelota (int nx, int ny)
{
pelotaX= nx;
pelotaY= ny;
this.ancho=this.getWidth();
this.alto=this.getHeight();
repaint();
}

// Here we receive from the game container class the key pressed
public void keyPressed(KeyEvent evt)
{
switch(evt.getKeyCode())
{
// Move ship 1
case KeyEvent.VK_W :
player1FlagArr = true;
break;
case KeyEvent.VK_S :
player1FlagAba = true;
break;

// Move ship 2
case KeyEvent.VK_UP:
player2FlagArr=true;
break;
case KeyEvent.VK_DOWN:
player2FlagAba=true;
break;
}
}

// Here we receive from the game container class the key released
public void keyReleased(KeyEvent evt)
{
switch(evt.getKeyCode())
{
// Mover Nave1
case KeyEvent.VK_W :
player1FlagArr = false;
break;
case KeyEvent.VK_S :
player1FlagAba = false;
break;

// Mover nave 2
case KeyEvent.VK_UP:
player2FlagArr=false;
break;
case KeyEvent.VK_DOWN:
player2FlagAba=false;
break;
}
}

// Move player 1
public void moverPlayer1()
{
if (player1FlagArr == true && jug1Y >= 0)
jug1Y += abajo;
if (player1FlagAba == true && jug1Y <= (this.getHeight()-25))
jug1Y += arriba;
dibujarPlayer1(jug1X, jug1Y);
}

// Move player 2
public void moverPlayer2()
{
if (player2FlagArr == true && jug2Y >= 0)
jug2Y += abajo;
if (player2FlagAba == true && jug2Y <= (this.getHeight()-25))
jug2Y += arriba;
dibujarPlayer2(jug2X, jug2Y);
}

// Position on Y for the player 1
public void dibujarPlayer1(int x, int y){
this.jug1X=x;
this.jug1Y=y;
repaint();
}
// Position on Y for the player 2
public void dibujarPlayer2(int x, int y){
this.jug2X=x;
this.jug2Y=y;
repaint();
}

public void run() {
// TODO Auto-generated method stub
boolean izqDer=false;
boolean arrAba=false;

while(true){

if(juego){

// The ball move from left to right
if (izqDer)
{
// a la derecha
pelotaX += derecha;
if (pelotaX >= (ancho - 8))
izqDer= false;
}
else
{
// a la izquierda
pelotaX += izquierda;
if ( pelotaX <= 0)
izqDer = true;
}


// The ball moves from up to down
if (arrAba)
{
// hacia arriba
pelotaY += arriba;
if (pelotaY >= (alto - 8))
arrAba= false;

}
else
{
// hacia abajo
pelotaY += abajo;
if ( pelotaY <= 0)
arrAba = true;
}
dibujarPelota(pelotaX, pelotaY);

// Delay
try
{
Thread.sleep(50);
}
catch(InterruptedException ex)
{

}

// Move player 1
moverPlayer1();

// Move player 2
moverPlayer2();

// The score of the player 1 increase
if (pelotaX >= (ancho - 8))
contPlay1++;

// The score of the player 2 increase
if ( pelotaX == 0)
contPlay2++;

// Game over. Here you can change 6 to any value
// When the score reach to the value, the game will end
if(contPlay1==6 || contPlay2==6){
juego=false;
gameOver=true;
}

// The ball stroke with the player 1
if(pelotaX==jug1X+10 && pelotaY>=jug1Y && pelotaY<=(jug1Y+25))
izqDer=true;

// The ball stroke with the player 2
if(pelotaX==(jug2X-5) && pelotaY>=jug2Y && pelotaY<=(jug2Y+25))
izqDer=false;
}
}
}

}


So, now we save and compile both classes and run the Main class.
So, its play time.
Like you will see, there is a bug with the game. When it starts, both scores are in 1, i didn't try to fix it but if somebody fix it i really will appreciate if you post how :D
 

Looking for more tutorials on game programming, check out the below links:

Making Terrain In UDK

Making Terrain In UDK Part 2 Texture

The XNA Tutorial - Part 1

 




#644196 What programming language is the best?

Posted by mbcev on 11 November 2012 - 01:50 PM

Honestly I don't believe any of those are going to be substantially better or worse for producing games. If RollerCoaster Tycoon was produced almost entirely in assembly, I'm pretty sure you could do fine reproducing it in any of the languages presented.

There's a misconception today that Java is slow; it simply isn't anymore so that's a null argument.  How mod-able a game is has nothing to do with it being written in Java or not but rather how you write the game. If you create the proper framework to allow others to change content whether it be through a scripting system, api calls, or something else entirely, that is up to you. The Elder Scrolls series have fairly active modding communities surrounding them and the Elder Scrolls games weren't put together using Java. So again, that argument is null. Lastly, and as much as I love Java, the idea of it being "easily portable" really only goes so far. No language, including Java, is necessarily perfectly portable. Your Java code will only work in an environment with a JVM which is capable of executing your code. That means that depending on how you handle various portions of your application, you may lose your beloved portability. For example say you're doing the graphics portion using a graphics engine which opts not to operate in the JVM but instead interface more directly with OS. Well if that's the case, suddenly you have an OS dependent and library dependent game that you can't merely copy paste onto a new platform and hope to see it churn butter. So again, also not necessarily a good example. As you said, Minecraft is written in Java. Why hasn't it been completely ported to Android yet? Because it isn't as easy as a simple copy paste. So that argument is also invalid.

C++ has some aspects to it which some people find difficult, sure (such as pointers). But that hasn't stopped anyone from using it to produce fantastic games because fantastic games are produced by fantastic people for whom using pointers isn't quite so scary. All that supposed speed that C++ applications have comes mainly from using the pointer system actually. So if you end up choosing to avoid using that part of the language because it is hard, you really aren't reaping the benefits of that system. Overall, however, as I implied there are going to be far more difficult problems that you face in writing a game than how to deal with pointer arithmetic properly so if you can't handle that, you won't be able to handle the bigger challenges. If you aren't creating overly large and expansive games but rather starting small with things like Tetris and Asteroids... well then it doesn't matter which language you use then does it?

C#: I'd argue that C# is effectively just Microsoft's Java instead of Oracle (previously Sun Micro systems) Java. C# does have some additional features such as delegates, but again what good to you is that if you don't know what they are and how to use them correctly? And since frankly down to the level of syntax C# and Java are almost identical in nature, C# isn't any harder or easier to use. Also the Mono project in Linux has been a very extensive effort to produce an open CLR (Common Language Runtime.... essentially the same as JVM which is Java Virtual Machine) which runs natively in Linux. And when I say that it is extensive, I do quite mean it. The greater majority of the CLR functions have been reproduced in Mono so really you should have pretty much the same "copy paste" portability that you have with Java in that regard (which remember as I stated, is actually a lot more limited than you may have thought originally).

Finally, in regards to

I can't go and randomly choose a programming language and then later coming back and saying : "Man, fahk dat :thumbdown: , i'm gonna learn dat other language!".  


If you aren't willing to learn then you're not going to make very much progress in Computer Science. Unless you already know what you're doing and are very well established, you aren't going to be able to produce any interesting or noteworthy games, I'm sorry. But that isn't any reason to give up. You pick a language and or tool set and you start learning everything there is to learn and solving all the problems that you come into contact with. I started my programming career learning C but it isn't something I use anymore. I also brushed up on C++ for a time, again not something I use on a daily basis. I continued on to learn Java, my language of choice, and as I said I tend to use that for most everything I do today but that wasn't the last language I learned. I also went on to learn C#. I've used C# for a multitude of projects and if necessary I would opt to use that framework for a project if I felt that Java and the JVM couldn't suit me. In order to expand my JVM abilities, I am currently attempting to teach myself Clojure. For work I'm also exploring the GWT framework for rich web applications as well as HTML5, CSS3, and Javascript.

No matter what you're doing and what you're exploring you really do just need to work at it because regardless of if you spend your time learning to build games in Java, C++, or C#, you are still going to be learning valuable programming lessons. Being a programmer isn't about what languages you know, it's about solving problems. I can solve the same problem in Java and C# and neither one of them will realistically be overly "better" than the other. This is especially true because in the grand scheme of things, those three languages all fall into the same category of language anyway. The problem solving methodology is going to be largely similar no matter what you do. It isn't until you pick up another programming paradigm that you realize how laughably similar the options you presented are.

TL;DR version: C++ is probably the way to go because you're already a little familiar with it, there are a ton of tools and resources for game development in C++, and it still maintains some of the lower level complexities that other languages have opted out of including so you'll learn a thing or two both about how computers work and how other languages that mask those complexities work as well.


#629380 Creating A Simple Yet Secured Login/registration With Php5

Posted by papabear on 08 May 2012 - 03:28 PM

Hello everyone here's a new simple tutorial by me, I know that there's a lot of login and registration php script in this section but as I've review them.. some aren't secured and some still uses the php4 functions and some are weak and can be attack using SQL Injection that's why I decided to write up a tutorial that uses some new PHP5 functions that can help you in making your simple yet secured Login and registration script.

The very first thing that you have to do before we start is to create a database into your phpmyadmin

CREATE DATABASE `codecalltut` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `codecalltut`;


CREATE TABLE IF NOT EXISTS `users` (
  `userID` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) NOT NULL,
  `password` varbinary(250) NOT NULL,
  PRIMARY KEY (`userID`,`username`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

So we now have our database for this project. Let's create the login form now, create a file and name it index.php
then paste this login form in it.


<!DOCTYPE html>
<html>
	<head>
		<title>Codecall Tutorials - Secured Login with php5</title>
		<link rel="stylesheet" type="text/css" href="style.css" />
	</head>
	
	<body>
	
		<header id="head" >
		 <p>Codecall tutorials User Login</p>
		 <p><a href="register.php"><span id="register">Register</span></a></p>
		</header>
		
		<div id="main-wrapper">
		 <div id="login-wrapper">
			 <form method="post" action="">
				 <ul>
					 <li>
						 <label for="usn">Username : </label>
						 <input type="text" maxlength="30" required autofocus name="username" />
					 </li>
					
					 <li>
						 <label for="passwd">Password : </label>
						 <input type="password" maxlength="30" required name="password" />
					 </li>
					 <li class="buttons">
						 <input type="submit" name="login" value="Log me in" />
							<input type="button" name="register" value="Register" onclick="location.href='register.php'" />
					 </li>
					
				 </ul>
			 </form>
				
			</div>
		</div>
	
	</body>
</html>

then create a new file and name it register.php and paste this code inside that file


<!DOCTYPE html>
<html>
	<head>
		<title>Codecall Tutorials - Secured Login with php5</title>
		<link rel="stylesheet" type="text/css" href="style.css" />
	</head>
	
	<body>
		<header id="head" >
		 <p>Codecall tutorials User Registration</p>
		 <p><a href="register.php"><span id="register">Register</span></a></p>
		</header>
		
		<div id="main-wrapper">
		 <div id="register-wrapper">
			 <form method="post">
				 <ul>
					 <li>
						 <label for="usn">Username : </label>
						 <input type="text" id="usn" maxlength="30" required autofocus name="username" />
					 </li>
					
					 <li>
						 <label for="passwd">Password : </label>
						 <input type="password" id="passwd" maxlength="30" required name="password" />
					 </li>
						
						<li>
						 <label for="conpasswd">Confirm Password : </label>
						 <input type="password" id="conpasswd" maxlength="30" required name="conpassword" />
					 </li>
					 <li class="buttons">
						 <input type="submit" name="register" value="Register" />
							<input type="button" name="cancel" value="Cancel" onclick="location.href='index.php'" />
					 </li>
					
				 </ul>
			 </form>
			</div>
		</div>
	
	</body>
</html>

we know have all our form set, let's style our form a bit. create a new file and name it style.css then paste this


/* Css RESET */

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}

/* Styling the Header */
header#head {
background-color:#333333;
height: 50px;
width: 100%;
}

header#head p {
font-family: Arial, Helvetica, sans-serif;
font-size: 17px;
color:#999;
font-weight: bold;
padding: 20px;
}

header#head p #register {
float: right;
margin-top: -60px;
}

header#head p a:hover #register {
color:#999;
}

/* Styling the main wrapper */
#main-wrapper {
width: 100%;
height: 100%;
}


/* Styling the login wrapper */
#login-wrapper {
margin: 0px auto;
width: 310px;
height: 180px;
padding: 50px 1px 10px 50px;
margin-top: 150px;
-moz-box-shadow: 0px 0px 10px #888;
-o-box-shadow: 0px 0px 10px #888;
-webkit-box-shadow: 0px 0px 10px #888;
-moz-border-radius: 10px 10px 10px 10px;
-o-border-radius: 10px 10px 10px 10px;
-webkit-border-radius: 10px 10px 10px 10px;
}

#register-wrapper {
margin: 0px auto;
width: 310px;
height: 250px;
padding: 50px 1px 10px 50px;
margin-top: 150px;
-moz-box-shadow: 0px 0px 10px #888;
-o-box-shadow: 0px 0px 10px #888;
-webkit-box-shadow: 0px 0px 10px #888;
-moz-border-radius: 10px 10px 10px 10px;
-o-border-radius: 10px 10px 10px 10px;
-webkit-border-radius: 10px 10px 10px 10px;
}

/* Form height, margin, padding */
form ul {
	list-style: none;
	margin: 0;
	padding: 0;
}

form ul li {
	margin: .9em 0 0 0;
	padding: 0;
}

form * {
	line-height: 1em;
}

/* field labels */

label {
	clear: left;
	text-align: right;
	width: 15%;
	font-family: arial;
	font-weight: bold;
	font-size: 15px;
	color: #808080;
}

/* the fields */

input {
	font-size: .9em;
}

input {
	border: 2px solid #666;
	-moz-border-radius: 5px;
	-webkit-border-radius: 5px;
	border-radius: 5px;
	background: #fff;
}

input {
	display: block;
	margin: 0;
	padding: .4em;
	width: 80%;
}

/* Place a border around focused fields */

form *:focus {
	border: 2px solid #7c412b;
	outline: none;
}

/* Display correctly filled-in fields with a green background */

input:valid {
	background: #efe;
}




/* Submit buttons */

.buttons {
	text-align: center;
	margin: 20px 0 0 -80px;
}

input[type="submit"], input[type="button"] {
	display: inline;
	margin: 0 5px;
margin-left:20px;
	width: 10em;
	padding: 10px;
	border: 2px solid #7c412b;
	-moz-border-radius: 5px;
	-webkit-border-radius: 5px;
	border-radius: 5px;
	-moz-box-shadow: 0 0 .5em rgba(0, 0, 0, .8);
	-webkit-box-shadow: 0 0 .5em rgba(0, 0, 0, .8);
	box-shadow: 0 0 .5em rgba(0, 0, 0, .8);
	color: #fff;
	background: #ca5f34;
	font-weight: bold;
	-webkit-appearance: none;
}

input[type="submit"]:hover, input[type="submit"]:active, input[type="button"]:hover, input[type="button"]:active {
	cursor: pointer;
	background: #fff;
	color: #ef7d50;
}

input[type="button"]:active, input[type="button"]:active {
	background: #eee;
	-moz-box-shadow: 0 0 .5em rgba(0, 0, 0, .8) inset;
	-webkit-box-shadow: 0 0 .5em rgba(0, 0, 0, .8) inset;
	box-shadow: 0 0 .5em rgba(0, 0, 0, .8) inset;
}




here's the look of our login and registration page now
registration.JPG
login.JPG

ok everything was set.. let's get into coding! create a new file and name it config.php we are going to use this file to store every constant and settings for our project. Paste this code inside config.php

<?php
	//set off all error for security purposes
error_reporting(0);


//define some contstant
	define( "DB_DSN", "mysql:host=localhost;dbname=codecalltut" ); //this constant will be use as our connectionstring/dsn

	define( "DB_USERNAME", "root" ); //username of the database
	define( "DB_PASSWORD", "" ); //password of the database
define( "CLS_PATH", "class" ); //the class path of our project

?>

Everything was explained inside the codes with comment :)

let's now create our Users class, this class will contain the function or registering and logging into our project.

create a new folder and name it class then inside that folder create a file named user.php open the file and let's start.

first let's create the class


<?php

class Users {

}

?>

What is a class? Classes are objects that contains useful functions to use in your programs. If you are an OOP(object oriented programmer) you will encounter Classes many times. Classes can be used for data hiding like encapsulation, abstraction and polymorphism.

let's declare the public/global variables that we will use into this class


class Users {
	 public $username = null;
	 public $password = null;
	 public $salt = "Zo4rU5Z1YyKJAASY0PT6EUg7BBYdlEhPaNLuxAwU8lqu1ElzHv0Ri7EM6irpx5w";
}

$username= we are going to use this variable to be able to store and get the values of our form easily by just calling $this->username.

$password = like $username this variable will be use to store and get the password in the form.

$salt = salt will be use for hashing/encrypting our password.

let's create our first function in this class


public function __construct( $data = array() ) {
			   if( isset( $data['username'] ) ) $this->username = stripslashes( strip_tags( $data['username'] ) );
			  if( isset( $data['password'] ) ) $this->password = stripslashes( strip_tags( $data['password'] ) );
}

Is this your first time seeing that __construct? __construct is one of the magic methods and it was introduced in PHP5. What is the use of __construct? The moment you call the class or create an instance of it or use it's variable, the __construct method will be executed automatically. This is a useful function for storing data to your public variables.

if( isset( $data['username'] ) ) $this->username = stripslashes( strip_tags( $data['username'] ) );
if( isset( $data['password'] ) ) $this->password = stripslashes( strip_tags( $data['password'] ) );

the parameter $data in our __construct class is an associative array and. If we pass the $_POST into this method knowing that our $_POST from the form will have something like $_POST['username'] and $_POST['password'].
this two condition there was just organizing the data and removing the slashes and html tags for security we used stripslashes() and strip_tags() functions.


Let's now create a function that we can use to get the $_POST into our form and give it to our __construct method.


public function storeFormValues( $params ) {
			  //store the parameters
			  $this->__construct( $params );
}

we will use this to get the $_POST from our forms something like Users->storeFormValues($_POST) and then we will store those values into our __construct class.

let's create the login function


public function userLogin() {
				   //success variable will be used to return if the login was successful or not.
				   $success = false;
				  try{
					 //create our pdo object
					 $con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
					 //set how pdo will handle errors
					 $con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
					 //this would be our query.
					 $sql = "SELECT * FROM users WHERE username = :username AND password = :password LIMIT 1";

					  //prepare the statements
					 $stmt = $con->prepare( $sql );
					 //give value to named parameter :username
					 $stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
					 //give value to named parameter :password
					 $stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
					 $stmt->execute();

					 $valid = $stmt->fetchColumn();

					if( $valid ) {
						  $success = true;
					 }

					 $con = null;
					 return $success;
				 }catch (PDOException $e) {
					  echo $e->getMessage();
					  return $success;
				 }
}

If you can see I used PDO for my database connection and manipulation.
Why? Because it supports prepared statements and named parameters. For a basic tutorial of using the PDO Connection Please go into this thread -> Using PDO for Database Access (Beginner)

In the code above there are comments that will teach what the code is doing, and you will encounter a line that uses this

hash("sha256", $this->password . $this->salt)

what is that by the way?
it is the hash() function that was introduced to PHP5 recently. With the use of that function it's now easy to encrypt a string with different algorithms.


md2		   32	
md4		   32
md5		   32
sha1		  40
sha256		64
sha384		96
sha512	   128
ripemd128	 32
ripemd160	 40
ripemd256	 64
ripemd320	 80  
whirlpool	128
tiger128,3	32
tiger160,3	40
tiger192,3	48
tiger128,4	32
tiger160,4	40
tiger192,4	48
snefru		64
gost		  64
adler32		8
crc32		  8
crc32b		 8
haval128,3	32
haval160,3	40
haval192,3	48
haval224,3	56
haval256,3	64
haval128,4	32
haval160,4	40
haval192,4	48
haval224,4	56
haval256,4	64
haval128,5	32
haval160,5	40
haval192,5	48
haval224,5	56
haval256,5	64

how to use it?
hash(algorithm, stringtohash . salt)
salt is optional but it's highly recommended to use it for an advance security.
In this tutorial I uses the sha256 encryption algorithm.

let's continue, here's our registration function




public function register() {
	 $correct = false;
	 try {
			  $con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
			  $con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
			  $sql = "INSERT INTO users(username, password) VALUES(:username, :password)";

			  $stmt = $con->prepare( $sql );
			  $stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
			  $stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
			  $stmt->execute();
			  return "Registration Successful <br/> <a href='index.php'>Login Now</a>";
	   }catch( PDOException $e ) {
				 return $e->getMessage();
	   }
}


same as the login we use the  
hash("sha256", $this->password . $this->salt)

our class is now complete and here's the complete Users class code.


<?php

class Users {
public $username = null;
public $password = null;
public $salt = "Zo4rU5Z1YyKJAASY0PT6EUg7BBYdlEhPaNLuxAwU8lqu1ElzHv0Ri7EM6irpx5w";

public function __construct( $data = array() ) {
if( isset( $data['username'] ) ) $this->username = stripslashes( strip_tags( $data['username'] ) );
if( isset( $data['password'] ) ) $this->password = stripslashes( strip_tags( $data['password'] ) );
}

public function storeFormValues( $params ) {
//store the parameters
$this->__construct( $params );
}

public function userLogin() {
$success = false;
try{
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM users WHERE username = :username AND password = :password LIMIT 1";

$stmt = $con->prepare( $sql );
$stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
$stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
$stmt->execute();

$valid = $stmt->fetchColumn();

if( $valid ) {
$success = true;
}

$con = null;
return $success;
}catch (PDOException $e) {
echo $e->getMessage();
return $success;
}
}

public function register() {
$correct = false;
try {
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "INSERT INTO users(username, password) VALUES(:username, :password)";

$stmt = $con->prepare( $sql );
$stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
$stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
$stmt->execute();
return "Registration Successful <br/> <a href='index.php'>Login Now</a>";
}catch( PDOException $e ) {
return $e->getMessage();
}
}

}

?>

sorry if there's no indention, When I pasted the code from my code editor from here the indention was missing.

Everything was set up, we now have a class where we can use login and registration, now we must include it to our config.php.

open up config.php and paste this code below to include our class

 //include the classes
include_once( CLS_PATH . "/user.php" );

then open up the index.php once again and let's include our config.php and use the class functions.
paste this code at the very top of your index.php


<?php 
include_once("config.php");
?>

<?php if( !(isset( $_POST['login'] ) ) ) { ?>

then paste this code at the very bottom of your index.php


<?php 
} else {
$usr = new Users; //create a new instance of the Users class
$usr->storeFormValues( $_POST ); //like I said before we will use the function storeFormValues to store the form values

if( $usr->userLogin() ) {
echo "Welcome"; 
} else {
echo "Incorrect Username/Password"; 
}
}
?>

the index.php will now look like this.


<?php 
include_once("config.php"); //include the settings/configuration
?>

//if user did not click the login button show the login form
<?php if( !(isset( $_POST['login'] ) ) ) { ?>

<!DOCTYPE html>
<html>
    <head>
        <title>Codecall Tutorials - Secured Login with php5</title>
        <link rel="stylesheet" type="text/css" href="style.css" />
    </head>
    
    <body>
    
        <header id="head" >
         <p>Codecall tutorials User Login</p>
         <p><a href="register.php"><span id="register">Register</span></a></p>
        </header>
        
        <div id="main-wrapper">
         <div id="login-wrapper">
             <form method="post" action="">
                 <ul>
                     <li>
                         <label for="usn">Username : </label>
                         <input type="text" maxlength="30" required autofocus name="username" />
                     </li>
                    
                     <li>
                         <label for="passwd">Password : </label>
                         <input type="password" maxlength="30" required name="password" />
                     </li>
                     <li class="buttons">
                         <input type="submit" name="login" value="Log me in" />
                            <input type="button" name="register" value="Register" onclick="location.href='register.php'" />
                     </li>
                    
                 </ul>
             </form>
                
            </div>
        </div>
    
    </body>
</html>

<?php 
//else look at the database and see if he entered the correct details
} else {
$usr = new Users;
$usr->storeFormValues( $_POST );

//if our function userLogin() returns true then the user is valid, display welcome else say it's incorrect.
if( $usr->userLogin() ) {
echo "Welcome"; 
} else {
echo "Incorrect Username/Password"; 
}
}
?>


index.php is done, let's now edit our registration.php

add this at the very top of the file


<?php 
include_once("config.php"); //include the config
?>

//if user did not click registration button show the registration field.
<?php if( !(isset( $_POST['register'] ) ) ) { ?>

and this code at the very bottom of the file like the index.php


<?php 

//if register button was clicked.
} else {
$usr = new Users; //create new instance of the class Users
$usr->storeFormValues( $_POST ); //store form values

//if the entered password is match with the confirm password then register him
if( $_POST['password'] == $_POST['conpassword'] ) {
echo $usr->register($_POST); 
} else {
//if not then say that he must enter the same password to the confirm box.
echo "Password and Confirm password not match"; 
}
}
?>



The End.

the tutorial is now done, and we've manage to create a simple yet secured login and registration!
I've attached the project files and the database backup for you to download it.
Have fun guys

Attached File  codecall.zip   5.2K   2467 downloads


#527827 Printing ASCII Code

Posted by Egz0N on 26 November 2009 - 02:58 AM

Hello CodeCall Members,

Today I'd like to Show you How to Make a Simple Program that Will Print us the ASCII Code .. using C++ ..

Ok..!  ,

First of all we declare 2 variables .. ('i' as an integer and 'a' as a character)

int i;
char a;


then we use this loop:

for (i=30;i<=255;i++)

the "i" starts from 30 because the other characters before 30 are some special characters (like ENTER etc..) .. so we say that from i=30 till i<=255 increasing the 'i' for 1 ..


the 'a' character becomes the character with the ASCII code 'i' ..  using this command ..

a=i;

now, using "iomanip" we format the output .. the iomanip code will look like as following:

        cout << setw(2)
             << a
             << setw(6)
             << i;


.. the "setw(2) will reserve 2 spaces for the character 'a' .. and setw(6) will reserve 6 spaces for the number 'i'  ..


finally the code will look like the following:

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    int i;
    char a;
    
    for (i=30;i<=255;i++)
    {
        a=i;
        cout << setw(2)
             << a
             << setw(6)
             << i;
    }
    cout << endl;
    
    return 0;
}


.. and the console application will look like the following:

http://forum.codecall.net/attachment.php?attachmentid=2363&stc=1&d=1259233059 ..


Thanks,

Egz0N ..

Attached Images

  • ASCII.JPG

Attached Files




#493640 Polygon tutorial

Posted by Turk4n on 28 July 2009 - 01:12 PM

Hello and welcome to a CodeCall Java tutorial. Today I will talk about Pentagons in Java and how you can draw one also using it for fun with javas buildin GUI set; swing.
Firstly we all no what a Pentagons is, however for those unfamiliar with what a pentagons is here is an example of a pentagon.
Posted Image

So mainly a pentagon is a five edged figure. So how do I draw a pentagon with swing?
Well let's get going and do the thing.

Step #1
Make the pentagon(Object !)

Import the needed packages

Packages
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

Create the object

Class
public class Pent extends JPanel implements ActionListener {

Add up the needed variables
private int n,r;
	private double angle;
	private int[] x,y;
	private double dv = 5*2*Math.PI/360;
	private double turn = 0.0;
	private Timer tim = new Timer(100, this);

What are our variables for? Firstly we need two integers which represents the sum of every part and time. We need angle to deiced the angle of our pentagon you could do as you suit with it later on. We need two arrays to represent the 2-D figure. Dv will represent our edges and turn how much it will turn since I want to show one possibility with swing why not show off?
tim presents the time it will take to go around and around the world...


Build up functions

Pentagon

public Pent(int pieces, int radie) {
		n=pieces; r=radie;
		x = new int[n];
		y = new int[n];
		angle= 2*Math.PI/n;
	}
Our pentagon will take form soon, this is it's bones...

Start and Stop
public void start() {
		tim.start();
	}
	public void stop() {
		tim.stop();
	}

Movement of our pentagon
public void actionPerformed(ActionEvent E) {
		turn= turn+dv;
		if(turn>2*Math.PI)
			turn-= 2*Math.PI;
		repaint();
	}

Pentagon behavior
public void paintComponent(Graphics G) {
		super.paintComponents(G);
		int x0 = getSize().width/2;
		int y0 = getSize().height/2;
		
		for(int i=0; i<n; i++) {
			double v = i*angle- turn;
		x[i] = x0 + (int)Math.round(r*Math.cos(v));
		y[i] = y0 + (int)Math.round(r*Math.sin(v));
		}
		G.fillPolygon(x, y, n);
	}
}
Here we are actually filling the figure in a component that will we later present up into a frame with a start and stop button. The math.round presents the rotation that will happen.
Lets work on the main class now.

Main packages
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

Main class
public class PentDemo extends JFrame implements ActionListener {
Main variables
private JButton On= new JButton("On");
	private JButton Off = new JButton("Off");
        private JPanel a = new JPanel();
	private Pent p = new Poly(5,50);
We are going to use a Frame as our container for the Panel which will contain the pentagram allowing us to have it in a fine motion without disturbance, you could do it on the frame if you like to instead of my way. As we do not extend from the Pentagon class(pent) instead we are creating a reference to it and adding values to the constructor.

The main constructor and GUI build...
public PentDemo() {
		add(y,BorderLayout.CENTER);
		add(a,BorderLayout.SOUTH);
		a.add(On); a.add(Off); 
		On.addActionListener(this);
		Off.addActionListener(this);
		setSize(200,180);
		setVisible(true);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setTitle("Pentagon");
	}
Simple frame build adding the components Panel and our Pent into the frame allowing us to use it for our own purpose I guess :X?(LOL).
Note as I told before you can add everything directly to the Frame we are extending from, instead of using a seperate Panel.(the variable called 'a')


Actions
public void actionPerformed(ActionEvent e) {
		if(e.getSource() == On) {
			y.start();
		}
		else
			y.stop();
	}
As we using our reference from pent we can use methods inside from pent to our main, which is start and stop...

The main application...
public static void main(String[] arg) {
		PentDemo pd = new PentDemo();
	}
}
And that's about it hope you enjoy this vague tutorial and hopefully you will do something more creative than I did...
Cheers !

Output
Posted Image
[ATTACH]1858[/ATTACH]

Attached Images

  • Pentagon.png



#430551 A Simple Notepad In C#

Posted by Kierien on 30 January 2009 - 09:10 PM

Harlo,

This guide wont teach you to code some awesome notepad but just a simple one..Im going to try to keep the code as simple as possible.

Aite, your gonna need to open a new C# project by opening Microsoft Visual C#, then goto

File>New>Windows Form Application

Name the project Notepad or whatever you want.

Add the following items. (Menu Strip, openFileDialog, saveFileDialog, Text Box)

Posted Image

Now set the textBox's dock to fill, then rename it to txtMain.

Posted Image

Then click one time on your textBox, you should see a small play arrow, click it and check "Multiline".

Posted Image

You should now have something that looks like this.

Posted Image

Now right click on a blank part of the menu strip, and press "Insert Standard Items"

Posted Image

You should have a bunch of basic functions by now, but its not that easy =P, they all dont have code.

But start off by deleting "Tools" and "Help".

Now in your form editor click on the "File" button, then double click on "New", which should bring you to the code editor, then write the code

txtMain.Clear();

Then goto "Open"'s code, and add this code

//Shows the openFileDialog
openFileDialog1.ShowDialog();
//Reads the text file
System.IO.StreamReader OpenFile = new System.IO.StreamReader(openFileDialog1.FileName);
//Displays the text file in the textBox
txtMain.Text = OpenFile.ReadToEnd();
//Closes the proccess
OpenFile.Close();

Now proceed to "Save"'s code, and add this code

//Determines the text file to save to
System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(openFileDialog1.FileName);
//Writes the text to the file
SaveFile.WriteLine(txtMain.Text);
//Closes the proccess
SaveFile.Close();

Then for "Save as"'s code, add

//Open the saveFileDialog
saveFileDialog1.ShowDialog();
//Determines the text file to save to
System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(saveFileDialog1.FileName);
//Writes the text to the file
SaveFile.WriteLine(txtMain.Text);
//Closes the proccess
SaveFile.Close();

"Print"'s code is

//Declare prntDoc as a new PrintDocument
System.Drawing.Printing.PrintDocument prntDoc = new System.Drawing.Printing.PrintDocument();

"Print Preview" is

//Declare preview as a new PrintPreviewDialog
PrintPreviewDialog preview = new PrintPreviewDialog();
//Declare prntDoc_PrintPage as a new EventHandler for prntDoc's Print Page
prntDoc.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(prntDoc_PrintPage);
//Set the PrintPreview's Document equal to prntDoc
preview.Document = prntDoc;
//Show the PrintPreview Dialog
if (preview.ShowDialog(this) == DialogResult.OK)
{
//Generate the PrintPreview
prntDoc.Print();
}

"Exit"'s code is

Application.Exit();

Move on to "Undo"'s code, add

txtMain.Undo();

For "Redo"'s code its

txtMain.Undo();

Add this to "Cut"'s code

txtMain.Cut();

For "Copy" add

txtMain.Copy();

"Paste"'s code is

txtMain.Paste();

For "Select All" its

txtMain.SelectAll();

Ur done with most of the code, but our Notepad still lacks one function - Word Wrap!!

Quote from Xav:

I disagree with the last bit (the word wrap). It would be much better to use a single checked box to wrap text.

To achieve this, set the menu item's CheckOnClick boolean property to True, and then use the following code in the Click event:

txtMain.WordWrap = wordWrapMenuStripItem.Checked




Well thats it =)

Posted Image

Hope you enjoyed this guide. If you need anymore screenies tell me lol, i'll add em.

~kierien


#421851 Determinants Value

Posted by MathX on 03 January 2009 - 04:55 AM

This is a very simple tutorial that shows how to create a simple program in VB6 to calculate the value of a determinant.

First - Create 3 new forms.

On form1 put a combo box and change its text to "Choose"
Create a command button too and on the caption write "Go!"

Posted Image

As it is shown on the screen shot on the list write "2x2" and "3x3".

Posted Image

Double click on the button and write those lines of code:

Private Sub Command1_Click()
If Combo1 = "2x2" Then
Form2.Show
Else
Form3.Show
End If
Unload Me
End Sub

On form2 put 5 textboxes and a command button.
Change the caption of the Command button to "Calculate"

Posted Image

Double click on the Button and write this line of code:

Private Sub Command1_Click()
Text5 = Text1 * Text4 - Text2 * Text3
End Sub

This is the formula to calculate the value of 2x2 determinant.


On form3 put 10 textboxes and a command button.
Change the caption of the Command button to "Calculate".

Posted Image

Double click on the Button and write this line of code:

Private Sub Command1_Click()
Text10 = Text1 * Text5 * Text9 + Text3 * Text4 * Text8 + Text2 * Text6 * Text7 - Text3 * Text5 * Text7 - Text1 * Text6 * Text8 - Text2 * Text4 * Text9
End Sub

This is the formula to calculate the value of 3x3 determinant.


This is my first tutorial ever so, I apologize for any mistakes.

PS: Thanx to SaintLion


#524064 Div Deque?

Posted by BlaineSch on 09 November 2009 - 02:42 PM

So I was trying to make something for a project and though I might need a deque for the project I was working on. Not knowing a ton about OOP inside of JS or how various things pass (reference or copy) etc I thought this would be a realistic approach for what I needed. When I got done I realized this would be a great tutorial since it was so easy to make.

What is a deque? A deque is a double ended que. Most of you are familiar with it, but for those who are not, a stack is like a stack of plates. You put one plate on the top, and when you want the plate again you pick it up. First in last out. A deque is double ended so its kinda like those plates are hovering in the air, and you can put plates on the bottom and on the top and take one off from either end as well.  If that was a horrible explanation click here.

The idea behind this is having a div, and inside of that div I will use JS to move around there.

So lets start off making a div, set the id to something we can remember "deque" seems appropriate to me. Add a input box and submit box to help us add things as well. I put an id on the text box as well since we will need the value.

<input type="text" value="" id="insert">
<input type="submit" value="Push!">
<!-- Nodes here! -->
<div id="deque"></div>


To make this work should not be too hard, basically get the deque by the id, create a new div and add the content inside of it (innerHTML) then use javascripts "appendChild" to insert it into the bottom of the list.

<script>
function Push() {
//declare variables
var mydeque = document.getElementById('deque'); //gets the deque
var nodevalue = document.getElementById('insert'); //gets the input box
var mynode = document.createElement('div'); //creates a div

//insert
mynode.innerHTML = nodevalue.value; //sets the value
nodevalue.value = ""; //resets input box
mydeque.appendChild(mynode);
}
</script>
<input type="text" value="" id="insert">
<input type="submit" onclick="Push();" value="Push!">
<!-- Nodes here! -->
<div id="deque"></div>


Now we need to be able to add from the top, so we going to basically do the same approach, add a dropdown so we know which side to add too, instead of appending were going to use "insertBefore" in javascript to add them.

<script>
function Push() {
//declare variables
var order = document.getElementById('side'); //gets the oder 0 = first element, 1 = second
var mydeque = document.getElementById('deque'); //gets the deque
var nodevalue = document.getElementById('insert'); //gets the input box
var mynode = document.createElement('div'); //creates a div

//insert
mynode.innerHTML = nodevalue.value; //sets the value
nodevalue.value = ""; //resets input box
if(order.options.selectedIndex==0) {
mydeque.insertBefore(mynode, mydeque.firstChild);
} else {
mydeque.appendChild(mynode);
}
}
</script>
<input type="text" value="" id="insert">
<select id="side">
<option>Top</option>
<option>Bottom</option>
</select>
<input type="submit" onclick="Push();" value="Push!">
<!-- Nodes here! -->
<div id="deque"></div>


Now to get values! This is really easy to do, were going to alert the value, and then remove the child using "removeChild" and with that use "firstChild" or "lastChild" so really simple.
<script>
function pop(id) {
if(id==0) {
//top
var deque = document.getElementById('deque');
alert(deque.firstChild.innerHTML);
deque.removeChild(deque.firstChild);
} else {
//bottom
var deque = document.getElementById('deque');
alert(deque.lastChild.innerHTML);
deque.removeChild(deque.lastChild);
}
}
</script>


And the finished script, I added a little color to make it easier on the eyes!


Posted Image


<html>
<head>
<title>Div Deque!</title>
<style>
div.glow0 {
border-left:4px solid #952fa4;
padding: 0px 0px 0px 4px;
}
div.glow1 {
border-left:4px solid #40af0e;
padding: 0px 0px 0px 4px;
}
div.glow2 {
border-left:4px solid #3d769e;
padding: 0px 0px 0px 4px;
}
</style>
<script>
var i = 0;
function Push() {
//declare variables
var order = document.getElementById('side');
var mydeque = document.getElementById('deque');
var nodevalue = document.getElementById('insert');
var mynode = document.createElement('div');

//insert
mynode.setAttribute('class', 'glow'+ (i%3));
mynode.innerHTML = nodevalue.value;
nodevalue.value = "";
if(order.options.selectedIndex==0) {
mydeque.insertBefore(mynode, mydeque.firstChild);
} else {
mydeque.appendChild(mynode);
}
i++;
}
function pop(id) {
if(id==0) {
//top
var deque = document.getElementById('deque');
alert(deque.firstChild.innerHTML);
deque.removeChild(deque.firstChild);
} else {
//bottom
var deque = document.getElementById('deque');
alert(deque.lastChild.innerHTML);
deque.removeChild(deque.lastChild);
}
}
</script>
</head>
<body>
<a href="javascript:pop(0)">Pop from Top!</a> | <a href="javascript:pop(1)">Pop from Bottom!</a><br />
<input type="text" value="" id="insert">
<select id="side">
<option>Top</option>
<option>Bottom</option>
</select>
<input type="submit" onclick="Push();" value="Push!">
<div id="deque"></div>
</body>
</html>



#494755 BlaineSch's SEO Tutorial

Posted by BlaineSch on 01 August 2009 - 10:34 AM

BlaineSch's SEO Tutorial

First of all lets just get this straight. I do not claim to be an "expert" by far on this subject. I know some tricks which I have learned from other tutorials and a few I have picked up myself. I will simply go over things I would suggest you do for your website to help it in the long run. Not always directly dealing with SEO but to help it overall. If you are not familiar with what SEO is it is called "Search Engine Optimization" which basically is a bunch of tips and tricks people use to have better rankings, call PageRank, in various search engines like Google or Yahoo or MSN's Bing.

Why Validate?
There are lots of things to consider when building a website, this in my opinion is not one of them. Most tutorials I have read through would say stuff like "Validate your Code!". Just by looking at different sites I believe this is a waste of time unless you are offering HTML services. Out of Yahoo, Google, and Bing, none of them passed. If they are the major search engines and they do not care then I doubt you should care either.

The HTML Stuff
When I build a website I try to keep in mind that it would be very difficult for a search engine to tell that a span with a class should have more emphasis than another span with a different class. I try to make sure I use h1-6 tags for more emphasis instead of spans. That way search engines can tell what words are more important. I also try to describe each image with alternate (alt) text, and each link with a title description as well. Meta tags are a way of the past but most sites still use them and I recommend still using them as well. Here is an Meta Tag Generator, and here is a Keyword Generator for you to use to help you with this part of it.

Unique Content
Unique content is a must for all websites. If you have a bunch of duplicate content you site will be marked as spam from search engines and you will get a VERY low ranking. If you do not have much text on your website try having a professional blog on there as well. If it is an image website with just a bunch of images you will get a low ranking even if you have alternate text and stuff since almost all of your pages look exactly the same in the HTML part of it. It is not hard to write unique content about a particular subject at all. If writing is not your strong suit then I would sugest finding a freelance content provider.

Make sure a lot of your pages do not contain the same content as well. Even if it is the same page say "page1.php?ssid=123" and "page1.php?ref=http://www.google.com" Google will cache them both and start marking your unique content as duplicate content which may result in a spam flag on your site. Some other things I would just like to point out is frames. I hate them, never use them, they will never come in handy that much, they are annoying in every situation. Also, do not forget to spell check everything you write. Incorrectly spelled words are very annoying to lots of people and makes you look unprofessional. Try and throw the keywords you picked above in the articles and things you make.

Digg what?
Most websites offer users the ability to "digg" their page. I find this very refreshing. This does not specifically help your SEO but it will increase traffic which I believe Google and others may use an estimate on traffic to determine relevancy as well. I have seen a few websites with a "Submit bar" or whatever you want to call it which will allow you to submit that page to like 10 websites. If it is a good page, why not also allow the users to email the page to a friend, allow them to comment on the page, and even even have an easy for for users to "Link Back" to the page by providing them with the direct link. Here is a free script I found just by doing a quick Google search: Add to Bookmarks.

Links too and from
Links are very powerful in SEO. When the age of Google began, they simply saw sites that contained a keyword 100 times getting a higher rank which is obviously spam, so they figured it one site linked to another site that site was less likely spam. In my opinion the more links you have to your site the better, most people end there, I also believe that you should have sites linking to relevant sites yourself. Some people will get a few sites linking to their site and that's it, If Google visits your site, then realizes it has nowhere else to go it stops and I believe this will hurt your PR/SEO. You should link to relevant sites as well. When writing in a blog or something I usually link to sites that I may reference or just randomly linking too or a wiki page about a word or phrase I do not want to explain.

You should also have a "link back" feature. I have seen Google blog do this and found it to be a wonderful idea to manage external links. Basically if they link to page1 then page1 would link to it in return. I set it up so I approve domains, not every page cause that would be impossible, but basically if "domain1.com/page1.html" links to me and then "domain1.com/page2.html" links to me as well I have already approved domain1.com so I do not need to approve it again. I may post the script for this if somebody asks for it.

Getting Links
This can be a costly experience for most, but if you look at it the right way there are lots of ways to do this for free. If you are looking to pay for it, go to my "Advertise" section. There are many ways to go about doing this part of the process under a nice budget. One would be finding link exchanges which basically mean you agree to put a link on your site, to their site and vise versa. Others ways would be to go to a web forum or somewhere that allows signatures and things and be an active user, do not just be an active spammer, try and post unique content on their site as well. Even if your site has unique content, going on a forum that is the same subject like an article on a "Programming" forum would also help your "Freelance" website. If some of your posts have unique content and Google decides to index the page. Try putting a link in your signature on your email as well, this can be very helpful to getting a few more people to your website. Try making a unique article somewhere and posting it, or making a Wiki page that would allow a link to your site for a reference or something. I would discourage link directories, mainly because it goes against a previous statement I made. Most directories do not have relevant or unique content and probably do not have many links going back to them.

Advertising
This subject should be a tutorial of it's own so I will make it brief. Advertising is a big part of how you get customers to your website, and possibly how you make money from them. There are many advertising services out there, like Adsense or Adwords. To make money from your website if you do not offer a service you may want to put ad's on your website which is perfectly normal, but where do you place them? What colors work best? I believe that the more people see the ad, the more likely they will click it, so if the page is stretching down, then put the ad going down so its more visible while they are reading. With colors, usually I see people "Blend it in" like if they have a website with a black background and white text they realize if they put that kind of ad in the middle of their article they will get more links, because it does not look like advertising but relevant links to other websites. I would recommend making a rotators of ads and colors and see which ones work best.

Long and Short URL's
I have heard lots of blabbing about URL's recently. My opinion on these is very very simple actually. I would say rewriting the URL is not a bad thing, but keep it short. Search engines do not like extremely long URL's and neither do users. If you do rewrite then keep it short. If you do not try and get a few keywords, and still keep it short.
Try and avoid things like:
  • site.com/page1.php
  • site.com/page2.php
Also avoid:
  • site.com/pages.php?page=1
  • site.com/pages.php?page=index
  • site.com/pages.php?page=contact
And also:
  • site.com/here_are_some_pages_I_created_using_dreamweaver_for_you.php?id=index_page&ssid=2340230482340&bksl2=social&ref=Google&keyword=Long_Urls
I am sure you get the idea. Just keep it simple and clean. I have heard some other dumb things like "Does Google care about the extension? .html or .php?" and in my opinion I do not think Google really cares much. Google, Yahoo, Bing, neither of them even list an extension when searching for something. It will not file all html pages as "static" or all PHP pages as "Dynamic" just because not all html pages are static and not all php pages are dynamic.

Tutorial Info
You are free to edit and redistribute this tutorial as long as you include this information wherever you post it. This tutorial was made by BlaineSch located at www.BlaineSch.com if you have any questions feel free to post them in this thread or email me at BlaineSch@gmail.com


#471674 CodeCall Info

Posted by Vswe on 11 June 2009 - 11:34 AM

Title: CodeCall Info

Description: A little program I made to see how far way you are from all the codecall ranks (Guru , Code Warrior etc.). See Additional Info for more info :P

Language:
This program is written in VB.Net.

Additional Info:

In the form you can write your CodeCall username and password.

Posted Image

Then the program will log in to CodeCall and check your post count, Rep count and join date.

Posted Image

When it's done you can select which of the Guru, Code Warrior, Code Slinger and Code master's progress you want to show. You can select all of them if you want.

Posted Image


By pressing 'Receive Info' the program will check CodeCall again while pressing 'Update list' will only update the list according to the settings but with the info from the last check.

Here's how a list can look like (It's mine :D):

Posted Image

Tested System: This is only tested on Windows Vista but it should work on other window versions.

Requirements (if any are known): You need a CodeCall account to have anything to check :P

License: Do what you want with it. But don't blame me if you print the code and eat it up and gets a Belly-ache :P.

Operating Systems: Windows

Features:
See Additional Info

Todo List: I won't add anything but you could do it.

Source/Binary Attachment:
Guru.zip is the source code.
CodeCall Info.zip only contain one .exe file. It's the program only.

Attached Files




#423088 C++/opengl –part3 : creating simple game

Posted by amrosama on 07 January 2009 - 12:13 PM

Hi codecallers,
This is the third and last part of the c++/opengl tutorials series, this one is different because we will use all the stuff we learned in the previous two parts to create a simple 2d game
The game will be like this:
http://forum.codecall.net/attachment.php?attachmentid=1230&stc=1&d=1231358977

As you can see it will be really simple and fun
First we start by drawing our objects in the “DrawGLScene(GLvoid)” , instead of putting the code directly into the function we will write the code of the drawing in separate functions because we can use these objects more than once,
Now lets draw every object in the output above:
1.The borders of the window:
We have two borders wit different location that’s why we use functions instead of writing the same code and changing only one variable, the function that draws the borders will be like this:
void border(float posx,float posy,float posz)
{
	glLoadIdentity();

glTranslatef(posx,posy,posz);
glBegin(GL_QUADS); 

glColor3f(0.0f,0.0f,1.0f); 

glVertex3f( 0.5f, 20.0f, 0.0f); //up right corner

glVertex3f( -1.0f, 20.0f, 0.0f); //up left corner

glVertex3f(-1.0f,-20.0f, 0.0f); //down left

glVertex3f( 0.5f,-20.0f, 0.0f);//down right

glEnd();
}
Nothing new in the code, we only put the code in a separate function that takes three arguments with the location


2.Player and pc :
These two object are the same but with different locations that’s why we use the same function for them both:
void playerno1(float posx,float posy,float posz)
{
	glLoadIdentity();

glTranslatef(posx,posy,posz);
glBegin(GL_QUADS); 

glColor3f(0.0f,1.0f,1.0f); //red

glVertex3f( 6.0f, 2.0f, 0.0f); //up right corner

glColor3f(1.0f,1.0f,0.0f); //red

glVertex3f( -6.0f, 2.0f, 0.0f); //up left corner

glColor3f(1.0f,0.0f,1.0f); //red

glVertex3f(-6.0f,0.0f, 0.0f); //down left

glColor3f(0.0f,1.0f,0.0f); //red

glVertex3f( 6.0f,0.0f, 0.0f);//down right

glEnd();
}


3.The ball:
void ball(float posx,float posy,float posz)
{
glLoadIdentity();

glTranslatef(posx,posy,posz);
glColor3f(1.0f,1.0f,1.0f);
glBegin(GL_QUADS);
glBindTexture(GL_TEXTURE_2D, texture[1]);
glTexCoord2f(0.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, 0.0f); //up right corner

glTexCoord2f(1.0f, 1.0f);
glVertex3f( -1.0f, 1.0f, 0.0f); //up left corner

glTexCoord2f(1.0f, 0.0f);
glVertex3f(-1.0f,-1.0f, 0.0f); //down left

glTexCoord2f(0.0f, 0.0f);
glVertex3f( 1.f,-1.0f, 0.0f);//down right

glEnd();
}
I bet you thought that we used a new shaped called circle or something, but no we used a regular quad but wih this texture:
http://forum.codecall.net/attachment.php?attachmentid=1232&stc=1&d=1231359187

When we put these stuff I the “DrawGLScene(GLvoid)” it will look like this:
ouble playerpos=0;
double pcpos=0;
double ballx=0;
double bally=0;
int DrawGLScene(GLvoid) 
{
//calculate_movements();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 
glLoadIdentity(); 

//ball
ball(ballx,bally,-40);

//player
playerno1(playerpos,-16.5,-40.0);


//pc
playerno1(pcpos,14.5,-40.0);

//left border
border(-22.0,0.0,-40);

//right border
border(22.5,0.0,-40);

glEnd();
return TRUE; 
} 
If you tried this code you will notice that the objects wont move, that’s because the variable with the location is zero
First the user can control the quad at the bottom using the arrows, but he cant move it all the way to the left, it must stop when it hit any of the borders, we did that using this code in the keyboard input function:
void Keyboard_Input()
{
	if((GetKeyState(VK_LEFT) & 0x80))
	{
		if(playerpos>=-15.5)playerpos-=.09;
	}

	if((GetKeyState(VK_RIGHT) & 0x80))
	{
		if(playerpos<=15.5)playerpos+=.09;
	}
	if(GetKeyState('A')& 0x80)
	{
		if(start)start=false;
		else start=true;
	}
}
When the playerpos changes the bottom quad will change with the new playerpos value, the same concept aply to the ball and the upper quad but their values will be assigned by the computer not the user, that’s why we created a function called “calculate_movements()” that runs in the beginning of the drawglscene(), here it’s code:
double ballx=0;
double bally=0;
double ballspeed=.05;
bool updown=false;
bool leftright=true;
void calculate_movements()
{
//ball movement
if(start)
{
//these two statements check if the ball have crossed any of the two borders
//and reverse the direction of the ball
if(ballx>20.45)leftright=false;
if(ballx<-20.45)leftright=true;
	
//updown variable is true when the ball is moving up and vice versa

if(!updown)
{
	//if its moving down, this mean that it can hit the player quad
	//we check if it hitted the layer quad here, if it did we revese the 
	//updown bool variable and icrease the ball speed
	if((bally>-16.5 && bally<-13.5)&&(ballx>playerpos-6 && ballx<playerpos+6))
	{
		updown=true;
     	ballspeed+=.01;
	}
	//if the next condition is true, that means that the ball have crossed the
	//limit under the quad, which means that the user have lost
	//we reset the position and speed of the ball here
	else if(bally<-16.5)
	{
		//MessageBox(NULL,"you have lost against your stupid pc","sorry!",NULL);
		bally=0;
		ballx=0;
		ballspeed=.05;
		start=false;
	}
}
else
{//same as above
    if((bally<16.5 && bally>13.5)&&(ballx>pcpos-6 && ballx<pcpos+6))
	{
		updown=false;
	    ballspeed+=.01;
	}
	else if(bally>16.5)
	{
		//MessageBox(NULL,"you have WON against your stupid pc","well done!",NULL);
		bally=0;ballx=0;ballspeed=.05;
				start=false;
	}
}

//the ball will move, when we set it position to a diffrent location
//and thats what happens here, if the ball is moving up, we increase the "y" position of the ball
//same with the ball "x" position
	if(updown)bally+=ballspeed;
	else bally-=ballspeed;
	if(leftright)ballx+=ballspeed;
	else ballx-=ballspeed;
}

//pc movement
// the pc will move according to the ball "x" position
//setting, you can move it slower by setting it to something less 
//than .2
if(start)
{
if(ballx>pcpos) pcpos+=.2;
else pcpos-=.2;
}
}
I explained everything in the comments, that’s all
This is the last part of the c++/opengl series , thank you for reading
Source code and comiled exe are attached , feel free to ask, rely , or comment or any part of this series
Cheers.

Attached Images

  • output.JPG

Attached Files

  • Attached File  src.zip   118.45K   2235 downloads
  • Attached File  1.bmp   192.05K   6295 downloads



#418372 The history and basic's of C

Posted by nicckk on 22 December 2008 - 04:03 PM

Hello all, this is a tutorial I wrote for my friend who wanted to get into C. I made a video for him to use however I cannot link it(Under 10 posts). The tutorial I wrote contains the basic history of C, and what C can do. Also included in it is the overused Hello World example. When your done reading let me know what you think, because I wish to keep writing tutorials.
Link:YouTube - Everything you need to know about C
________________________________________________________________

This tutorial focuses on the language C. I will be showing you the common Hello world example. However before we will go over some key points of the C language, including history and features. So here we go

Dennis Ritchie of Bell labs created C in 1972. Dennis and Ken Thompson both worked on developing Unix.  C did not just pop out of Ritchies mind, the C language is based of Thompson’s B language. Certain languages can perform certain tasks. For example BASIC was developed to resemble English so student could have an easier time learning it. C overall offers shortcuts that can reduce your workload.

C has features that computer science theory and practice find desirable. C encourages to break down code into functions, however we will talk about that later in the tutorial.  Also C is an efficient language. It is designed to be concise.  There is a lot more about the history and what C can do, but that will be a later tutorial. Now let’s get started.

Whenever programming you should start with a clean example of what you want done. For this example I want the code we write to print the statement “Hello World!”. The next stop is writing and compiling code. After you have a feel how your program works and feels its time to start debugging.  Your program can run, but there are probably still some bugs that you could find and fix, before the official launch of your million dollar program.  Debugging as a definition is finding and fixing problems in your code.

As I learned C I followed 7 basic steps; however I fell that one main point is missing. Here are the seven steps
1. Define the program objectives
2. Design the Program
3. Write the code
4. Compile
5. Run the program
6. Test and debug the program
7. Maintain and modify the program
I fell that there is a step missing between 6 and 7. What’s missing is distributing your code, witch we shall get into later.


Now we need to talk about supplies. For a program to exist it needs to be written. You can use any text editor, however I recommend one with syntax highlighting for the language you wish to write in. You also need a compiler, because a computer cannot understand written phrases, code needs to be compiled into machine code. Currently I use Devc++ 5.0 beta 9.2.

If features a text editor with syntax highlighting and a built in compiler. Make sure you download the version with minGW/gcc
Now you may be wondering what is syntax? I have mentioned this word before. Basically syntax is the grammatical arrangement of words in sentences, basically it has to do with grammatical concepts. As you can have a syntax error in English such as cheetahs run fast do, not only do you sound like Yoda but your sentence has syntax errors. Code can also have syntax errors, and they must be cleared of before you can compile.
Now finally let’s start writing the program. I talked about earlier what objective I want the program to complete.  C is a top to down language you start high up defining broad code, and work your way down to specific code.

First we need to add the include. The include pre-process instructions. Following the include is the main function, witch then is followed by other functions. Braces mark the beginning and end of each function. Note that parentheses cannot do this. It has to be braces(They look like this, {}). Now I will introduce you to the printf() function. It prints a message. The f is there to remind you it is a function. The printf function is similar to BASIC’s PRINT command.

So lets start coding, as you may recall we need to start the program with an include. I will be using stdio.h or standard input output header. So let’s add it. You must add the pound sign before the statement include so if you were to type it out it would look like this
#include <stdio.h>
Now we add the main function and brackets. Now we have
#include <stdio.h>
main()
{
}
Now I will add the printf function within the brackets.
#include <stdio.h>
main()
{
	printf(“Hello World!\n”);
}

So you may be wondering what the backslash n means. In C it means new line. You have to remember add a semicolon after every line of code in C or else you will receive a syntax error. Now I will show you how to run the program, or at least how I do it. Compile your code to the desktop. Now move it to a folder that you know were it is located. For example I use my temp folder,c:\temp. Open command prompt and type in cd (location here). Cd is the command for dropdown. Now type in the files name and it should run.

Now try writing a program yourself.  Try to code a program that can print
For he’s a jolly good fellow
For he’s a jolly good fellow
For he’s a jolly good fellow
Which nobody can deny
Remember you can hit enter to start a new line and type out the printf function with parentheses and quotation mark and it will show up on a new line. That’s it for now. My next tutorial will be on multiple functions in C.

Edit: Fixed some vocabulary, and added a section I forgot, and added a link to the video.


#376987 Pointers(CrashCourse)

Posted by LogicKills on 26 August 2008 - 05:56 PM

Pointers In C++ (Crash Course)


Before We Get Started:
First lets talk briefly about computer memory and how it's addressing works.
Just like your house, the computer has an address for every memory block.
However instead of 124 LeeT Haxz0r Street, it is in a hexadecimal format.
So it looks something like ~    0x00000000. Lets look at an example..

#include <iostream>

int main()
{
	int myInt;
	
	std::cout << "The address of \'myInt\' is: " << (&myInt) << std::endl;
	
	return 0;
}

Ok, lets analyze this code.
First we declare an variable of type int called 'myInt'.
Then we use 'std::cout <<' to print the address of the variable to the screen.
This is possible because of the little '&' symbol. This is called the address operator.
Okay let's compile this thing..

<Linux>
$ g++ example.cpp -o example
$
$./example
$The address of 'myInt' is: 0xbfcbfab0

_________

<Windows>
Dev C++..
[F9 Key]
note: If you are compiling and running on widows, and your window vanishes before you can see the output.. add one of these:
'cin.get();'
__________

Alright if you compiled and ran it successfully congrats, please note that the memory address will vary. Alright since you understand a little bit how addressing works lets move on to actual pointers.

__________

Okay, so now with that all out of the way what do 'pointers' actually do.
Well their name is actually the thing they do, they point.
What they do is point to another address, this could be the address of a variable or something a little more complex like a function (we won't cover that yet).
In the example above we found out the address of our int by using that handy little operator called the.... yep, you guessed it: The Address Operator!

Lets open up that program and actually use a pointer and not just print the address to the screen..
Get your IDE's ready!!

#include <iostream>

int main()
{
	int myInt;
	int* p_myInt = &myInt; // in this case p stands for pointer :p
	
	std::cout << "The address of \'myInt\' is: " << (&myInt) << std::endl;
	std::cout << "The address of my pointer \'p_myINt\' is: "<< p_myInt << std::endl;
	return 0;
}

Alright compile and run that!
Again the address will vary!

So for my output I got:
The address of 'myInt' is: 0xbfe52570
The address of my pointer 'p_myINt' is: 0xbfe52570

Hah!! The addresses match, so we successfully used a pointer.  
Alright, pretty cool eh?
Wouldn't it be cooler if you could actually see the value that is at that address?
Well it turns out you can :]

To do that we are going to use the '*' dereferencing operator!
We are going to edit that program again a minuscule amount, let's assign a value to myInt~
#include <iostream>

int main()
{
	int myInt = 6;
	int* p_myInt = &myInt; // in this case p stands for pointer :p
	
	std::cout << "The address of \'myInt\' is: " << (&myInt) << std::endl;
	std::cout << "The address of my pointer \'p_myInt\' is: "<< (p_myInt) << std::endl;
	std::cout << "The VALUE of myInt is : " << (myInt) << std::endl;
	std::cout << "The VALUE of *p_myInt is : " << (*p_myInt) << std::endl;
	return 0;
}

Compile and run it

Here is my output~
The address of 'myInt' is: 0xbfb2810c
The address of my pointer 'p_myInt' is: 0xbfb2810c
The VALUE of myInt is : 6
The VALUE of *p_myInt is : 6

_________

So let's get some things straight p_myInt is a pointer the value it holds is an address.
However *p_myInt is an int, the value it holds is what ever the current value is at the address.


<DANGERS>
When you create a pointer, your computer allocates memory for the address, but not for the data that will be at the address..

Example:

long* myPointer;
*myPointer = 13373773773;

So yes myPointer is a pointer, however we have neglected to say where it points address wise.
So this can cause major problems.
ALWAYS INITIALIZE YOUR POINTERS~!


__________

Alright so now you know a good amount about what pointers are an how they work, my next tutorial will be what you can do with pointer's and when they come in handy!

I hope this threw some light on the shady subject of pointers!

Next to come:
Using pointers, using new and delete, and some other fun stuff!

/LogicKills/


#651884 Interview: Lintwurm

Posted by BenW on 07 February 2013 - 05:01 PM

This week's interview is with lintwurm. I thought perhaps he really was a lintwurm, but apparently the various members here with animal related names all have them for reasons other than actually being that animal.

 

1. What is a lintwurm and where can I buy one?

 

This is actually quite a funny story. The word "Lintwurm" means Tapeworm in my native language Afrikaans which is 1 of 11 official South African languages. When I was studying at the University of Pretoria I was the only one in my group of friends that really loved C++, so whenever we had to do a project I would always do the Back End stuff and API's etc. And because I was always in the "inner workings" of the system my friends started calling me Lintwurm. So to answer your question about buying one, you'll have to travel back in time to the 1950's when they used tapeworms to induce fat reduction.


2. And can you tell us a bit about yourself?

 

I'm a pretty relaxed guy these days and I love coding. I code at work work on opensource software in the evenings. I studied at the University of Pretoria and got my BSc in IT 2 years ago. I am currently working, but would one day like to have my own company so I can work on opensource more.

 

3. Where is Pretoria, and what's it like there?

 

Pretoria is in South Africa. Side note: I am a caucasian male, this always amazes people. I've lived in South Africa my whole live. It's a beautiful country and I couldn't imagine living anywhere else. The crime can get a bit much though.

 


4. How long have you been programming for?

I actually haven't been coding for that long. My first experience was in University. This surprizes lots of people because I can program rather well. It just made sense to me and it is so beautifully logical. I have never thought about doing anything else since I started programming about 5 years ago.


5. And what's your biggest programming achievement so far?

 

I have 2 feats that I would like to share. My first one is an AI program that simulated playing in the stock market. I started it off with R1000 (Rand) and ended with R1 300 000! Too bad it's illegal to really use it! Second is a spell checker(yawn I know) that I implemented for the company I work at. I used a trie algorithm with a whole bunch of optimizations. It's blisteringly fast.

 

6. What programming-related goals do you have?

 

I have a dream of having coding standards at the company I work at. It annoys me to no end that there are no standards here. Everyone else seems fine with the way things are though :(

 

7. If you were an actual worm, what would you do all day?


I guess if I were a tapeworm I'd probably chill inside someone all day wondering why my life is so **(literally). If I were another worm I'd probably eat and sleep all day. And probably hope that no-one bites into the apple I'm in.


8. What hobbies do you have outside of programming?


I play a bit of guitar, I also play Dota2(if anyone wants a beta key, send me a message.) and I skateboard though I'm not anywhere as good as I used to be.


9. Tell us a funny (true!) story.

 

I went shopping with my mom and girlfriend not too long ago. My girlfriend was looking for clothes and my mom helped. My mom says that a pair of jeans look quite nice and my girlfriend says:"No, I'm growing a bit of a belly so it won't fit right...". My mom just gives me the:"is she pregnant" look and I just laugh it off. Next my girlfriend dashes off to a shirt that tickles her fancy and we follow suit. She then proceeds to take a pants of the shelf and it turns out to be maturnity wear. At this point my mom just snaps and straight out asks:"Is this how you're going to tell me you're expecting a baby". I have never laughed so hard in my life. Simple misunderstandings that got out of hand.

 

10. And your favorite joke?

 

My favorite programming related joke:"Why do Java developers wear glasses? Because they can't C#". Favorite
joke of all time: a neutron walks into a bar and orders a beer. The bartender gives him the beer. The neutron asks:"So how much?". Bartender replies:"For you, no charge". It's lame but I like it. Also, I recently made a shirt that has my favorite quote:"Alcohol and Calculus don't mix. Don't drink and derive"

 

11. What's your favorite programming language, and why?

 

My favorite language must be C++. I love searching for and destroying memory leaks. I like working close to the metal while still being able to comprehend what I read. I have mad respect for anyone who can do assembly. Those people are my idols.


12. And what do you like most about Codecall?

 

The friendly people here. If I accidently give someone a wrong answer, no one "yells(caps?)" at me for being stupid. I've learned so much in this forum.

 

13. Are you superstitious?

 

I am not really superstitious. Actually not at all :D

 

14. What's the worst programming mistake you've ever made?

 

I once took about 5 hours to find out that I had mistakenly made a if statement that does an assignment. For clarity:

if(var1 = SOME_ENUM)

return true;

This is 100% legal in C++, it wont even give you a warning. For the non-C++ devs it should be a double = otherwise the if is ALWAYS executed.


15. And finally, what one piece of advice would you give to a new programmer?

Perseverance. It takes long to really understand programming, I still learn new things all the time! Never stop learning! Also, don't forget your towel and coffee. The latter probably being more important.