Friday, January 6, 2012

Lets implement a simple Lisp Interpreter in Java

Edit 2015.03.20 : If you are really interested in implementing a LISP like language in Java, you can visit this, this and this

You are probably programing with C++, Java or .Net thingies but not Lisp. Why? Because it is the most beautiful language that human ever made :) Let me explain.

If you write in a programming language, you have to look and understand the interpreter's or compiler's principals. If you didn't do that yet, let me say, when you look inside an interpreter you will see a picture in which hundreds of objects being copied from one data structure to another called stacks. When you trace the interpreter, you will see nothing except those abstract data structures. The scene you will see is like a casino with hundreds of card dealers...

But when you program in Lisp, the interpreter exactly does what you write. There is no abstraction, no hacking. You will deal the cards in your fully controlled casino. Having knowledge about what the interpreter does is everything.

Lets look at the following Lisp expression

(+ 2 (+ 3 2))

which states that interpreter first will sum 2 and 3 and the gained number will be summed with 2. The result should be 7. How did we do that? Because of our primary school skills. Lets do that with a stupid machine that can only handle basic stack operations as in assembly language.

Suppose that we have a stack object and we are sequentially adding tokens into that stack. A token is defined as an atomic element of this expression. So our tokens are (, +, 2, (, +, 3, 2, ) and ) , respectively.

Now, take the first token and put it into the stack. Our stack is like that:


/


Lets add more elements until we encounter a closing parenthesis.


(+2(+32)

Again, suppose that, whenever we encounter a closing parenthesis, we collect some elements from the stack until we get an opening parenthesis, say that, we have now


(+32)

collected from the stack. Calculate this simple expression and put the result back to our stack. Since result of the sub expression (+ 3 2) is 5, our stack comes to shape of


(+25

We didn't finish reading the tokens yet. We have one more token to push into the stack.


(+25)

We encounter a closing parenthesis again and that means we have to handle the sub expression and put back the result to the stack. Since there is no sub expressions, we have the root expression at hand. Reading until having an opening parenthesis and performing calculations will give the result of 7 after all.

Note that, all we did here spans a 50 lines of Java class. I hope taking a glance at this code will help you to capture the whole story.



package smalllisp;

import java.util.Stack;

public class SmallLisp {

  Stack<String> stack;
  
  public SmallLisp(){
    String[] tokens = new String[]{"(","+","2","(","+","3","2",")",")"};
    stack = new Stack<String>();
    for (int i=0;i<tokens.length;i++){
      stack.push(tokens[i]);
      if(tokens[i].equals(")")) Interprete(); 
    }
  }
  
  public void Interprete(){
    String tok;
    Stack<String> callStack = new Stack<String>();
    tok = stack.pop(); /* This is the ) character */
    while(!(tok=stack.pop()).equals("(")){
      callStack.push(tok);
    }
    Call(callStack);
  }
  
  public void Call(Stack<String> callStack){
    String func = callStack.pop(); /* This is the operator or function */
    if(func.equals("+")) {
      double result = Plus(callStack);
      stack.push(String.valueOf(result));
    }
    //if(func.equals("-")) Minus(callStack);
  }
  
  public double Plus(Stack<String> callStack){
    double a = Double.parseDouble(callStack.pop());
    double b = Double.parseDouble(callStack.pop());
    System.out.println("Answer is "+(a+b));
    return(a+b);
  } 
  
  public static void main(String[] args) {
    new SmallLisp();
  }
}


Todo:
  • Implement the minus function yourself.
  • Implement the product function yourself.
Well done !

A Simple Qt Application Example using Qt Creator

Well, you are programming with C++ and you want to expand your programs with GUI components, Windows, Sockets, Threads, Timers and Processes. Since the standard C++ library does not include classes for those stuff, any C++ program needs external packages to cope with real world problems.

It is almost always a problem to find external libraries that provide platform independency. Java solves this problem with its standard API library which includes classes for threading, file operations, GUI stuff and networking. Qt does nearly the same thing. So, if you want to develop a program using a single framework, Qt is a good choice.

Although programming with Qt make people feel like programming in Java or any other "comfortable" language, do not forget that it is still C++. That means, you can be more relax in memory management but you are still face to face with the machine with your compiled code.

Qt is similar to Java as it is platform independent, that is, you will compile your source code in Windows, Linux and Mac and you will see the same running beautiful program.

If you are familiar with the Qt and you are seeking a framework to use in your C++ project, do not think any more and use it! And stop to read the remaining part of this text. If you don't know how to use it, follow the simplest Qt example in the world... Then have a Qt book and read it. You will feel comfortable with it after a month or two if you have ever programmed with Java or C++.

Yes, let's create a project. Download the Qt Creator from http://qt.nokia.com/products/ and install it. I suppose that you know how to install programs in your operating system. After a big installation progress, run the Qt Creator. You will see a window similar to this:


Then follow the menu "File >> New File or Project" and click it. A new window will be opened:


Select "Qt Widget Project >> Qt Gui Application" using the window then press "Choose".


Give a name for your project.



Select "Desktop" and click next.


Leave the class information as is and click next. When you learn how to program with Qt, you will need more than more window elements but a single one enough for our simple example.


Finally, we have a project which is ready to run. Unfortunately, it does nothing except showing an empty window. See your running empty form by typing CTRL + R key combination or click the menu "Build >> Run".


The panel on the left side shows our project configuration, .h (header), .cpp (C++ source) and gui (forms) files. You can simply activate by clicking on them. Lets click the "Forms >> mainwindow.ui" on the left side panel. 

Now, it seems our empty form is ready for designing. The left side panel now shows other GUI components which can be dragged and dropped on the empty form. Now find the Line Edit component under the "Input Widgets" group and drag & drop to the empty form. You can change its dimensions, name and other properties using the right side panels. But, leave it as is and find the push button component and create one on the form. 

We have now a filled form with a single textbox and a button. Since there is no action defined, when you run your program with the CTRL + R combination, you will see your form but push button does nothing when you click on it. Lets write something on the "text edit" when the push button is clicked. For those, we will add a code to mainwindow.h file. Select the mainwindow.h file and edit it like the following screenshot.


We added the code 

private slots:
    void pushbutton1_click();



in file mainwindow.h so we are able to define an action for the click event of the push button. Not that pushbutton1_click() is a function name which can be also selected as anything else. In Qt, we are controlling the user actions using a signaling mechanism. Every signal sender in Qt, defines SIGNAL 's. A signal catcher must define a SLOT for this. We want our code to catch the "clicking" signals from the push putton, so we defined a slot.

Now, select the mainwindow.cpp, which is the source code of our project and implement the function "pushbutton1_click()" which is defined in the corresponding header file.



void MainWindow::pushbutton1_click(){
    this->ui->lineEdit->setText("Qt Signals are easy");
}

We implemented the pushbutton1_click() in cpp file, which are defined in header file before. Now, we are quite ready because our program will put a "Qt Signals are easy" message on the this->ui->lineEdit object. Note that, lineEdit is the default name for this object and it is changeable by the user. Finally, we have to "link" the button's click action to MainWindow::pushbutton1_click() method. For that, edit the 



MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

to 

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->connect(this->ui->pushButton, SIGNAL(clicked()), this, SLOT(pushbutton1_click()));
}

So we have just connected the pushbutton's "clicked" signal to our pushbutton1_click() slot. That's all. Run the program.



After the compiling and running progress, click the push button and see the message on the text box.


SIGNAL  and SLOT mechanism is the most important thing in the Qt world to learn! Follow these steps to learn much:


  • Put a progress bar on the form. When we clicked to pushbutton, let the progressbar to show value of 50%
  • Create another pushbutton. When somebody clicks to pushbutton, show a message box containing a "Hello world!" text
  • Create a timer. Set the interval of timer to 1000 milliseconds (1 second). In each time the timer activated, show how many times the timer activated on the text box.
Read more books and tutorials and code something is not really meaningful. Qt is really easy to learn, especially, if you learned the SIGNAL & SLOT mechanism.

Good luck in your Qt life!




Sunday, December 4, 2011

Facebook Like Button Example With JQuery

Hi! We all got a Facebook account. As you remember, Facebook's got so much options that we can use, Like button, Chat, TimeLine etc.

In last article, I made mention of Jquery used within Facebook. Today, I'll show you one of'em. That is "like button".

As you know, when our friends share something, we can like it easily. When clicked the like button, data is saved without refresh. Because of this is JQuery&Ajax. Actually this example is not going to be like Facebook Like Button Module exactly, but, may be a good idea to do it for some of us. This things're so easy to do. We all need a database, a PHP page and a coding ajax page with ajax library, where is that complex?

Let's start it!

First, create your MYSQL Table;
CREATE TABLE `jquery_app`.`LikeButton` (
`ID` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`data` VARCHAR( 255 ) NOT NULL
)
You shall need this files:
  1. settings.php //database configurations
  2. jquery.js //your jquery code
  3. jquery library //you must include this file on index.php page
  4. match.php //your php code that you do like something and write database
  5. index.php //default page

index.php

This is facebook like button example. This is what i share! :)
< a href="#" id="like">Like < div id="whathappened"> //We see total clicked like button
< /div>
< div id="whathappening"> //We see what happening now
< /div>

When click the link, sending query to jquery.js page. After that jquery starts ajax method and searchs match.php page for adding +1.

jquery.js
// JavaScript Document
$(document).ready(function() {
 $('#like').click(function() {
  $('#whathappening').fadeIn(1000);
  var wait="Adding..";
  $.ajax({
   cache:false,
   async:false,
   url:'match.php',
   success:function(inc) {
    $('#whathappened').html(inc);
    $('#whathappening').html(wait);
    $('#whathappening').fadeOut(1000);
   }
  });
 });
});

When id=like click, data'll been added to database. If you ask how to add this, you should analyze the page is shown below.

match.php

 include("settings.php");
 //adding data
 $random=rand(0,99999999);
 $ekle=mysql_query("INSERT INTO LikeButton(data) values('$random')");
 //how many data we got
 //with the data we've just added
 $show=mysql_query("select * from LikeButton");
 $total=mysql_num_rows($show); //Getting total liked
 echo "Total: ".$total; //Print total liked.

What you see here, all php code. We include settings.php page for connection database. We get total and add +1 to this.

settings.php

 $conn=mysql_connect("localhost", "username", "password") or die("error1");
 mysql_query("SET NAMES 'utf8'") or die("error2");
 mysql_select_db("jquery_applications",$conn);
 error_reporting(0);
 ini_set('display_errors','Off');
 error_reporting(E_ALL); 

That's it! You've just done Facebook like module. If you want to see how to work this, you can visit the web site for demo.
Module view
When "Like" link click

Saturday, December 3, 2011

Cursed ad-hoc networking problem on Android


It is stil a problem to connect my Samsung Galaxy Tab P-1010 (Wi-fi only) to Internet
through my cell phone. Since Google does not do anything about this, people individually
seek for a solution for this. I have tried many compiled wpa_supplicant.so files on my device,
unfortunately, the only picture that I saw was a tablet computer without wi-fi support.

I have a new idea about this. I know it is not an elegant solution like debugging the source code of wpa_supplicant
and compile it for several devices.  But this is worth to share.

Firstly, suppose that we have an Android device with Wi-fi feature only and call it "Android Device". And suppose that we have a Java installed cell phone (it would be an S6 installed Nokia or Blackberry or an android cell-phone), and we will call it "Cell Phone". The development steps
for my solution are given below:

(Step 1) Implement a tiny http proxy for the Android Device. Suppose that, it listens from the port 8088.
(Step 2) Set the proxy settings on the web browser of Android Device, "localhost" for host and "8088" for port.
(Step 3) Implement a tiny JavaME application, which accepts URL's that sent by (Step 1) through a bluetooth connection, and downloads the
content of the accepted URL's and sends the content using the same bluetooth connection to the http proxy defined in (Step 1).


Now, we can expand those steps for our idea. Suppose that, the http proxy given in (Step 1) is connected to the JavaME application (Step 3) with bluetooth. There are many bluetooth protocols but I think (but I am not really sure about that)
the rfcomm type connection is the common type in both the JavaME and Android.

Whenever the proxy in (Step 1) accepts an URL, it sends this request to the JavaME application using the bluetooth connection.
The application defined in (Step 3) has an internet data plan, so it downloads the content and sends them to the proxy in (Step 1). 

Ok, not the best way, but it seems it would work.

Maybe, somebody wants to implement this.

Wednesday, November 30, 2011

How to Connect Cisco Router with PHP Scripts



I used to explain a Perl version of these scripts in page "http://stdioe.blogspot.com/2011/09/how-to-connect-cisco-router-with-perl.html". And now, I'm talking about the Php version. Because, Php is known to be easier than Perl by the most of the people. You may want to implement these samples in your existing projects. Essentially, we are establishing a telnet session between our script and a Cisco router. It's only a telnet connection. There are a lot of telnet-scripts for php in the internet. You can use them but we are talking about a specific situation. Let's write it from scratch.

I prepare to write those scripts as much as parametric, that is, I will avoid writing all of staff hard-coded. "$argv" variable is a predefined array in Php and it is able to capture the given parameters as well as in the console. For example,

<?php
#!/usr/bin/php
$if(isset($argv[2])) {
print "The first parameter is:".$argv[1]."\n";
print "The second parameter is:".$argv[2]."\n";
} else {
print "usage: ./sample.php parameter1 parameter2 \n";
print "or \n";
print "usage: php sample.php parameter1 parameter2 \n";
}

?>

You can execute the script by typing "./sample.php" or "php sample.php" directly in your console. If you want to execute it as "./sample.php", you have to add the line (#!/usr/bin/php) on the top of your script and you have to give executive permissions to sample.php. (chmod +x sample.php). If you want to execute with the syntax "php sample.php", you don't need to add the line and give those rights. Because, the executing rights are already given for "php" part.

The sample.php script is capturing your parameters using the array variable $argv. You can see all of the $argv content using the line "print_r($argv);" in you Php script. So we will use the $argv array to take ip_address, username and password values from the user. I used fsockopen, fput and fgets commands to establish connections, to send commands and to get the output from the router, respectively.

If the cisco router output is very long for one page, it returns a " -- More -- " statement in the last line. If we press the space button on the keyboard when we see this statement, the router will send next page. If we press the enter key on the keyboard when we see this statement, router will send the next line. So we have to control the content and if there is a " -- More -- " statement in the content, we have to send a space character to get next part of the router output. We will control the " -- More -- " statement with an "ereg" function of php.

The php script for connecting to the Cisco router (telnetCisco.php):

#!/usr/bin/php
<?php
if(!isset($argv[2])) {
die ("usage: ./scriptName router_ip username password\n");
}
$port = 23;
$timeout = 10;
$router_ip = $argv[1];
$username = $argv[2];
$password = $argv[3];

$connection = fsockopen($router_ip, $port, $errno, $errstr, $timeout);

if(!$connection){
echo "Connection failed\n";
exit();
} else {
echo "Connected\n";
fputs($connection, "$username\r\n");
fputs($connection, "$password\r\n");
fputs($connection, "show run\r\n");
fputs($connection, " ");

$j = 0;
while ($j < 16) {
fgets($connection, 128);
$j++;
}
stream_set_timeout($connection, 2);
$timeoutCount = 0;
while (!feof($connection)){
$content = fgets($connection, 128);
$content = str_replace("\r", '', $content);
$content = str_replace("\n", "", $content);
print $content."\n";

# If the router say "press space for more", send space char:
if (ereg('--More--', $content) ){ // IF current line contain --More-- expression,
fputs ($connection, " "); // sending space char for next part of output.
} # The "more" controlling part complated.

$info = stream_get_meta_data($connection);
if ($info['timed_out']) { // If timeout of connection info has got a value, the router not returning a output.
$timeoutCount++; // We want to count, how many times repeating.
}
if ($timeoutCount >2){ // If repeating more than 2 times,
break; // the connection terminating..
}
}
}
echo "End.\r\n";
?>

"stream_get_meta_data" function is the most critical one in this article. Because, I used the stream_get_meta_data to check the status of connection. Following output shows the "stream_get_meta_data" content with print_r function to see "how to recognize end of the output". (The last three loop)

....
...
Array
(
[stream_type] => tcp_socket
[mode] => r+
[unread_bytes] => 0
[seekable] =>
[timed_out] => 1
[blocked] => 1
[eof] =>
)
Array
(
[stream_type] => tcp_socket
[mode] => r+
[unread_bytes] => 0
[seekable] =>
[timed_out] => 1
[blocked] => 1
[eof] =>
)
Array
(
[stream_type] => tcp_socket
[mode] => r+
[unread_bytes] => 0
[seekable] =>
[timed_out] => 1
[blocked] => 1
[eof] =>
)

The time_out values are "1" in the last two loops. The $timeoutCount value is counting that "1"s in the telnetCisco.php and if it gets "1" more than two times, it stops reading the output with a "break;" line.