Monday, November 16, 2009

Introduction to Prolog

 

Prolog is a general purpose logic programming language associated with artificial intelligence and computational linguistics (Wikipedia Definition @ http://en.wikipedia.org/wiki/Prolog).

Prolog, LISP and many other languages depend on logic syntax and are represented as facts and rules. If you have any experience in programming using languages such as C#, JAVA or C++, then you need to change the way that you are using to write your codes.

How to start?

First of all, you need to download some tools to execute your commands; one of them is Amzi Development Environment. You can find it here: http://www.amzi.com/

What you have to do is just to open new file and write down your commands, then from Listener->Start you can start execute your code.

Code Syntax:

As we said in the beginning of this lesson, prolog depends on logical relationships, like:

 

Code Snippet
  1. Human(Ahmed)
  2. Car(Toyota)
  3. Human(Khaled)

This means that Ahmed and Khaled are humans. And Toyota is a car.

Let’s test those three lines; go to Listener -> Start then Listener -> Consult.

And in execution window, type the following question:

Code Snippet
  1. ?- Human(V).

Here we ask to show all humans and put it in array named V, you can press enter to quit or “;” to continue.

*** Note: (V) must be capital. All variables in Prolog must be capital.

The second type of questions is the Yes/No questions, like this:

Code Snippet
  1. ?- Human(Ahmed).

And you will get the answer depending on if you have added Ahmed to humans or not.

Relations:

In addition to previous, we can describe relationships between two items:

Code Snippet
  1. father(ahmed,mohammed)
  2. father(ahmed,ali)

So if we ask the engine this question:

Code Snippet
  1. ?- father(ahmed,U)

We will have all Ahmed's sons in U list.

Rules:

That is the point where we will start get benefit from prolog, this is the way that human brain works when thinking. For example (all cars have a door and all planes also):

Code Snippet
  1. car(X) :- gotadoor(X).
  2. airplane(X) :- gotadoor(X).

Then let's declare some planes and cars:

Code Snippet
  1. car(toyota)
  2. car(mazda)
  3. car(jagoar)
  4. airplane(ai100)

If we ask if mazda have a door or not, prolog engine will be smart enough to answer with yes.

More about Prolog:

This is just simple introduction to Prolog. There are a lot of features in Prolog you can start with from this link:

http://kti.mff.cuni.cz/~bartak/prolog/learning.html

Example:

Einstein Problem, one of the famous puzzles. Where the puzzle author (Einstein or anybody else) said that 98% of peoples can’t solve this problem:

There are 5 houses sitting next to each other, each with a different color, occupied by 5 guys, each from a different country, and with a favorite drink, cigarette, and pet. Here are the facts:

The Brit lives in the red house

The Swede keeps dogs as pets.

The Dane drinks tea

The green house is on the left of the white house

The green house's owner drinks coffee

The person who smokes Pall Mall rears birds

The owner of the yellow house smokes Dunhill

The man living in the center house drinks milk

The Norwegian lives in the first house

The man who smokes Blends lives next to the one who keeps cats

The man who keeps horses lives next to the man who smokes Dunhill

The owner who smokes Bluemaster drinks beer

The German smokes Prince

The Norwegian lives next to the blue house

The man who smokes Blend has a neighbor who drinks water

The question is: Who owns the fish?

If we try to translate this problem into Prolog group of facts, rules and relationships, it will be like this:

Code Snippet
  1. next_to(X, Y, List) :- iright(X, Y, List).
  2. next_to(X, Y, List) :- iright(Y, X, List).
  3. iright(L, R, [L | [R | _]]).
  4. iright(L, R, [_ | Rest]) :- iright(L, R, Rest).
  5. einstein(Houses, Fish_Owner) :-
  6. =(Houses, [[house, norwegian, _, _, _, _], _, [house, _, _, _, milk, _], _, _]),
  7. member([house, brit, _, _, _, red], Houses),
  8. member([house, swede, dog, _, _, _], Houses),
  9. member([house, dane, _, _, tea, _], Houses),
  10. iright([house, _, _, _, _, green], [house, _, _, _, _, white], Houses),
  11. member([house, _, _, _, coffee, green], Houses),
  12. member([house, _, bird, pallmall, _, _], Houses),
  13. member([house, _, _, dunhill, _, yellow], Houses),
  14. next_to([house, _, _, dunhill, _, _], [house, _, horse, _, _, _], Houses),
  15. member([house, _, _, _, milk, _], Houses),
  16. next_to([house, _, _, marlboro, _, _], [house, _, cat, _, _, _], Houses),
  17. next_to([house, _, _, marlboro, _, _], [house, _, _, _, water, _], Houses),
  18. member([house, _, _, winfield, beer, _], Houses),
  19. member([house, german, _, rothmans, _, _], Houses),
  20. next_to([house, norwegian, _, _, _, _], [house, _, _, _, _, blue], Houses),
  21. member([house, Fish_Owner, fish, _, _, _], Houses).

Then if you ask prolog this question:

Code Snippet
  1. ?- einstein(Houses, Fish_Owner).

You will have the right solution, try to use your mind to solve it and correct it with Prolog solution, if your answer not German, so you are Candidate to join the 98% club. It is not so bad :)

Sunday, November 1, 2009

Control Physical World Through Computer (Step by Step) - Part 3/3



Second Example, Driving Remote Control Car


What we will need?

      Remote Control Car.
      Relay.
      Transistor and Buffer (for security purpose only).
      Some wires.

Start

Again we will use the same concept; we will use Relay to control the power from the remote control.

If we try to open and remote, we will find this structure:

Control Physical World Through Computer (Step by Step) - Part 2/3



4- Tools

To start dealing with hardware, it is better if you have some tools to help you, such as

Breadboard:

coolcode6

It will help you to put your wires and pins; it contains connected line (5 pins for example) with the same value so you can read it from many places.


Control Physical World Through Computer (Step by Step) - Part 1/3



Introduction

coolcode1

In this article, we will take the first step inside physical computing world.

Physical Computing, in the broadest sense, means building interactive physical systems by the use of software and hardware that can sense and respond to the analog world. In physical computing, we take the human body as a given, and attempt to design within the limits of its expression. (Wikipedia Definition)

Background

To be able to understand this article, those things must be clear for you:

1- Binary System

As we all know, the only understandable commands for any computer is the (On/Off) power commands which represented as 0 and 1.

And for those two commands, we have only three logical operators. They are (AND, OR and NOT).

And: 1 AND 1 is 1, anything else is equal to Zero.

OR: 0 OR 0 is 0, anything else is equal to One.

Not: Not 1 is Zero, Not 0 is One.

Those three operators are implemented using transistors so they will be able to deal with electricity and give the result.

After that, we have started implementing many functions using those three operators. And collecting them in some electric circles called gates, using those only we are able to build what we call as IC which can perform more complex operations to the data, and for storage also using the concept of flip flops.

You don't need to understand all of this, but at least you must understand the general points of how we can build computer using only (0 and 1).


Saturday, October 31, 2009

StringBuilder



Most of us when we concat any strings, we are using (+) operator (or & in vb.net) this way:


// C#
Label1.Text = Text1.Text + "@hotmail.com";
// Vb.net
Label1.Text = Text1.Text & "@hotmail.com"


But .net framework provides us another way to concat strings, using StringBuilder which is under System.Text name space, this is how to use:


//C#:
System.Text.StringBuilder mail = New System.Text.StringBuilder(Text1.Text);
mail.Append("@hotmail.com");
'VB.net:
Dim mail As New System.Text.StringBuilder(Text1.Text)
mail.Append("@hotmail.com")


What is the difference?

When using (+,&), new object will initialized every time we use this operator. But with StringBuilder, we will use the same object.

From Net Gotachas book, the auther(Venka) assume simple concat operations within loop. And he run the loop using different maximum values of loops. This is snap shoot from the book representing the execution time:






3562.933 second is equal to 59.4 minutes. So will you still use (+,&)?

Finaly, StringBuilder gives us another operations such as Replace, Insert and Remove, you can find all about it with a graphs represent the diferent from this article in CodeProject:
http://www.codeproject.com/KB/cs/StringBuilder_vs_String.aspx


Different Between Const and static readonly



Declaring with const or static readonly will give the same result, we will have uneditable variable.

The only one difference is that (const) must take its value at compile time, but (static readonly) will take its value in run time.

so we can get more benefit from static readonly by declare it in static constructor:


class Program
{
public static readonly Test test = new Test();

static void Main(string[] args)
{
test.Name = "Program";
}



Monday, August 25, 2008

Introduction To WAP




Introduction:
Through this topic we will work together to understand Technology of Wireless Application Protocol (WAP), also we will take a fast tour about developing WAP Applications using ASP.net.

Technology Description:

Mobile Application :
When First Mobile arrived, it was only smart way for sending and receiving voice calls and after sometime for sending and receiving text messages. But now, it is become the most growing market for services and recreational purposes. It is also being used for accessing internet and multimedia world.

For this reason, a lot of developing and programming concepts changed to become compatible with mobile world, one of these concepts was WAP as a mobile alternative of WEB concepts for regular computers.

What is WAP ؟

From Wikipedia, WAP is an open international standard for application layer network communications in a wireless communication environment. Its main use is to enable access to the Internet (HTTP) from a mobile phone or PDA.

Sunday, August 24, 2008

Expression Blend



When WPF - the new .net technology- arrived, Microsoft try to provide some tools makes life easy to WPF Developers, one of this tools was Expression Blend, we will try to show some features about it in this topic.

Try to download it form Microsoft web site, then run it and choose new Project - WPF Application (*.exe):

You can now choose your name, folder and .net language you want.

Click View-Active Document View then click split view to show both code and design view:

Tuesday, June 17, 2008

IComparable Interface.



From The name, this Interface used for comparison. This is the implementation of this interface:

C#:

public interface IComparable
{
int CompareTo(object o);
}

vb.net:

Public Interface IComparable
Function CompareTo(ByVal o As Object) As Integer
End Interface

The result of this function is Integer; it returns 0 in similarity, -1 when the first one is smaller and 1 when larger .

Now we don't need to know who is larger, let’s assume that we have car class, something like that:

C#:

class Car
{

string Name;
int year;
}

vb.net:

Class Car
Private Name As String
Private year As Integer
End Class

Now we need to sort the cars depends on the creation year, our first step it to implement IComparable interface.

Thursday, June 5, 2008

FileSystemWatcher




FileSystemWatcher Class is very benefit when trying to monitor some files and inform user or program when any change occurs, all events are listed in NotifyFilters enum, this is the list of events can be handled by this:

public enum NotifyFilters {
Attributes, CreationTime, DirectoryName, FileName, LastAccess, LastWrite, Security, Size,
}

Now we need to declare functions to be called when some event occurred, this function will run through this delegate:


void MyNotificationHandler(object source, FileSystemEventArgs e)


Only rename event will run through this delegate:

void MyNotificationHandler(object source, RenamedEventArgs e)


Now we will start console application to monitor files, this application will run till user press q, this program will monitor all *.txt files in c:\ folder:


C#:


FileSystemWatcher watcher = new FileSystemWatcher();

// monitor files at:
watcher.Path = @"c:\";

// monitor files when
watcher.NotifyFilter = NotifyFilters.LastAccess NotifyFilters.LastWrite NotifyFilters.FileName NotifyFilters.DirectoryName;

// watch files of type
watcher.Filter = "*.txt";

// watch events:
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);

watcher.EnableRaisingEventys = true;

Console.WriteLine("Press 'q' to quit app.");

while (Console.Read() != 'q') ;

vb.net:


Dim watcher As New FileSystemWatcher()


' monitor files at:
watcher.Path = "c:\"

' monitor files when
watcher.NotifyFilter = NotifyFilters.LastAccess Or NotifyFilters.LastWrite Or NotifyFilters.FileName Or NotifyFilters.DirectoryName

' watch files of type
watcher.Filter = "*.txt"

' watch events:
AddHandler watcher.Created, AddressOf OnChanged
AddHandler watcher.Deleted, AddressOf OnChanged

watcher.EnableRaisingEvents = True

Console.WriteLine("Press 'q' to quit app.")

While Console.Read() <> "q"C

End While



As you seen, we call OnChanged function every event occurs, so we can implement this function to print this event and its time like that:


C#:


static void OnChanged(object source, FileSystemEventArgs e)

{

Console.WriteLine("File Changed, File Path: {0} , Change: {1}, DateTime: {2}", e.FullPath, e.ChangeType,DateTime.Now.ToString());

}

vb.net:


Private Shared Sub OnChanged(ByVal source As Object, ByVal e As FileSystemEventArgs)

Console.WriteLine("File Changed, File Path: {0} , Change: {1}, DateTime: {2}", e.FullPath, e.ChangeType, DateTime.Now.ToString())

End Sub


Now, this is screen shot of application when delete .txt file and create it again.




Friday, September 14, 2007

Introduction to AJAX in .net Applications



In the name of Allah.

Introduction to AJAX in .net Applications

Fast tour in Microsoft Ajax Toolkit

In this lesson we will take a fast tour in Microsoft Ajax world. First we have to know what the meaning of AJAX is.

AJAX or Asynchronous JavaScript and XML is a term describing a web development technique for creating interactive web applications using a combination of: HTML (or XHTML) and Cascading Style Sheets (CSS) for presenting information* Document Object Model, JavaScript to dynamically display and interact with the information presented* XML, XSLT and the XMLHttpRequest object to interchange and manipulate data asynchronously with the web server (although AJAX applications can use other technologies.