This blog serves as a place for me where I can occasionally dump bits of content from my brain. Feel free to browse.

‘Software & Website Development’ Category

Cyber Chat – Artificial Intelligence Chat-bot

It’s my new project in C++.

About Cyber Chat:

Cyber Chat is an Artificial Intelligence chatter-bot that interacts with the user in simple English language and can simulate a conversation. It has a repository or knowledge-base of patterns, which are matched with the input to give the best possible reply. More generally, the technique which is used in the knowledge-base to represent the Cyber Chat knowledge is known as “Case Base Reasoning” or CBR.

It has a large database consisting of 22 files.

- Download Link
- Sample Chat-log


C++ – Hanoi Towers Solution

Please don’t ask me how this code works! :)

#include <iostream>
 
using namespace std;
 
void hanoi(int n, char source, char intermediate, char destination) {
 
    if (n > 0) {
        hanoi(n - 1, source, destination, intermediate);
        cout << " - Moving disk " << n << " from " << source << " to " << destination << endl;
        hanoi(n - 1, intermediate, source, destination);
    }
 
}
 
int main() {
    int n;
    cout << "Enter the no. of disks: "; cin >> n;
    hanoi(n, 'A', 'B', 'C');
    return 0;
}

C++ – Quadratic Equation Solver

Functions:

checkRoots()
calculateRoots()

#include <iostream>
#include <iomanip>
#include <math.h>
 
using namespace std;
 
int checkRoots(double A, double B, double C) {
 
	int D = pow(B, 2) - 4 * A * C;
 
	if (D > 0) {
		return 0;
	}
	else {
		return D;
	}
 
}
 
void calculateRoots(double A, double B, double C) {
 
	double x1, x2;
 
	x1 = (- B + sqrt(pow(B, 2) - 4 * A * C)) / (2 * A);
	x2 = (- B - sqrt(pow(B, 2) - 4 * A * C)) / (2 * A);
 
	if (x1 != x2) {
		cout << "1. X = " << setprecision(5) << x1 << endl;
		cout << "2. X = " << setprecision(5) << x2 << endl;
	}
	else {
		cout << "X = " << setprecision(5) << x1 << endl;
	}
}
 
int main() {
 
	double A, B, C;
 
	cout << "Quadratic Equation Solver" << endl << endl;
 
	cout << "A = "; cin >> A;
	cout << "B = "; cin >> B;
	cout << "C = "; cin >> C;
 
	int result = checkRoots(A, B, C);
 
	cout << endl;
 
	if (result == 0) {
		calculateRoots(A, B, C);
	}
	else {
		cout << "Complex Roots" << endl;
		cout << "[Discriminant = " << result << "]" << endl;
	}
 
	return 0;
}

C++ List All Files in a Directory

If you need to do a certain task on all files or folders in a directory, the following code does the job. The following function recursively calls itself for all contained subfolders and prints all the files found. Note that this code will only run on Windows operating system as it uses Win32 API’s, namely FindFirstFile, FindNextFile and FindClose.

GetAllFiles() is called with the path of the base folder from where you want to start the enumeration.

Example Usage: GetAllFiles(“D:”);

Required Headers: <string> and <windows.h>


void GetAllFiles( string sPath )
{
    WIN32_FIND_DATA FindFileData;
    string sTmpPath = sPath;
    sTmpPath += "\\*.*";

    HANDLE hFind = FindFirstFile( sTmpPath.c_str(), &FindFileData );

    if ( hFind == INVALID_HANDLE_VALUE )
        return;
    else {
        do {
            if ( ( FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) ) {
		// if directory:
                if ( strcmp(".", FindFileData.cFileName ) && strcmp("..", FindFileData.cFileName) ) {
		    sTmpPath = sPath;
                    sTmpPath += "\\";
		    sTmpPath += FindFileData.cFileName;
                    GetAllFiles( sTmpPath.c_str() );
                }
            }
            else // if file:
            {
		sTmpPath = sPath;
                sTmpPath += "\\";
		sTmpPath += FindFileData.cFileName;
                cout << sTmpPath << endl;
            }
        } while ( FindNextFile( hFind, &FindFileData) != 0 );

        FindClose( hFind );
    }
    return;
}

C++ Bitwise Operations

Awhile ago, I was working on to create a bit array in order to compactly store individual boolean values. So that a typical 1 byte could be used to store an array of 8 boolean values (since each boolean value requires only one bit in order to be represented, i.e 0 or 1). This is a much better strategy, since on the other hand if we use simple array for storing 8 boolean values, it would take 8 bytes in memory instead of just one.

I created a class for this purpose which implemented this functionality and provided a clean interface to the user for using that array. However, I came to know later that such type of optimization is already done internally by the vector<bool> standard library, so it’s not particularly useful to code it ourselves.

I coded two functions for the purpose of setting individual bits ON or OFF in a byte. These functions perform the basic ON and OFF bit-wise operations and checking the status of a bit. So I thought it would be useful to share them with others too.

Functions for setting a particular bit ON or OFF in a byte:

Below is the code for the functions. This will give you some idea of how bit-wise operations can be used in C++ to perform some meaningful operation.

These functions do not return any values.

void setBitOn(unsigned int &value, int num) {
	const int SHIFT = num;
	const unsigned int MASK = 1 << SHIFT;
	value = value | MASK;
}
 
void setBitOff(unsigned int &value, int num) {
	const int SHIFT = num;
	const unsigned int MASK = 1 << SHIFT;
	value = value & (~MASK);
}

Function to check if a particular bit is ON or OFF:

bool checkBit(unsigned int value, int num) {
	const int SHIFT = num;
	const unsigned int MASK = 1 << SHIFT;
	return ((value | MASK) == value ? true : false);
}

Parameters defined:

In these functions, int num parameter is the offset of the bit which is to be reset. Thus num = 0 would be the right-most bit in the byte.
While, value is an unsigned int on which the operation is to be performed.

Example usage of the functions:

int main() {
 
	unsigned int x = 244;
	setBitOn(x, 0);   // set right-most bit to 1
	for (int i = 7; i >=0; i--) {
		cout << checkBit(x, i) ;
	}
	cout << endl;
	return 0;
 
}

Output of the above code would be: 11110101. Note that the binary of 244 is 11110100.

That’s all. I hope you learnt something from my code.

Happy coding, :)
Hassan


Login to website using VB.NET

The example below uses HttpWebRequest and HttpWebResponse classes to log in to Facebook.

Dim cookieJar As New Net.CookieContainer()
Dim request As Net.HttpWebRequest
Dim response As Net.HttpWebResponse
Dim strURL As String
 
Try
     'Get Cookies
     strURL = "https://login.facebook.com/login.php"
     request = Net.HttpWebRequest.Create(strURL)
     request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3"
     request.Method = "GET"
     request.CookieContainer = cookieJar
     response = request.GetResponse()
 
     For Each tempCookie As Net.Cookie In response.Cookies
            cookieJar.Add(tempCookie)
     Next
 
     'Send the post data now
     request = Net.HttpWebRequest.Create(strURL)
     request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3"
     request.Method = "POST"
     request.AllowAutoRedirect = True
     request.CookieContainer = cookieJar
 
     Dim writer As StreamWriter = New StreamWriter(request.GetRequestStream())
     writer.Write("email=username&pass=password")
     writer.Close()
     response = request.GetResponse()
 
     'Get the data from the page
     Dim stream As StreamReader = New StreamReader(response.GetResponseStream())
     Dim data As String = stream.ReadToEnd()
     response.Close()
 
     If data.Contains("<title>Facebook") = True Then
            'LOGGED IN SUCCESSFULLY
     End If
 
Catch ex As Exception
     MsgBox(ex.Message)
End Try

Now, here is some explanation:

Get Cookies

The following block of code gets all the cookies from Facebook and stores them in a collection. These cookies are returned upon visiting the webpage: https://login.facebook.com/login.php. Getting the cookies is very important, because they must be passed back to the webpage when you are going to login.

For Each tempCookie As Net.Cookie In response.Cookies
     cookieJar.Add(tempCookie)
Next

Passing post data to the website

Next, I created a StreamWriter class and wrote the post data to it. You can pass any data to the website here in name=value&name=value format.

Dim writer As StreamWriter = New StreamWriter(request.GetRequestStream())
writer.Write("email=username&pass=password")
writer.Close()

Finally…

The following code gets the source code of the webpage returned which is the homepage of your account (i.e home.php), and checks if you are logged in successfully or not.

Dim stream As StreamReader = New StreamReader(response.GetResponseStream())
Dim data As String = stream.ReadToEnd()
response.Close()
 
If data.Contains("<title>Facebook") = True Then
     'LOGGED IN SUCCESSFULLY
End If

I hope this simple example will help you save some time. If you find it useful then do let me know via your comments.

Happy Coding :)