Tuesday, October 16, 2012

Encryption Functions in PHP: crypt() and md5()

Hi! In this article, I am going to share encryption functions on PHP programming language with you. Well, there are several functions about this subject, but here the point is crypt and md5.


md5 function is a text encryption. Here the text or string may be probably as password. md5 function makes the text a value which is 32-digit. Sure this value is probably going to be more complex than older text value.
print md5("phpservisi.com");
md5 function's output
The example given above shows us phpservisi.com string value's output with md5 function.

crypt function is the same mission with md5. Namely this is encryption function too. Here the variety is complexity of output. Because of it is some of us use this one, like me :) 

One more feature is the output of crypt function's about making one-way string hashing. crypt function will return a hashed string using alternative algorithms that may be available on the system.

Now, I'm coding about this:


echo crypt("phpservisi.com"); 
echo "\n".crypt("phpservisi.com"); 
echo "\n".crypt("phpservisi.com"); 
echo "\n".crypt("phpservisi.com"); 
echo "\n".crypt("phpservisi.com"); 
echo "\n".crypt("phpservisi.com"); 
echo "\n".crypt("phpservisi.com"); 
echo "\n".crypt("phpservisi.com");

crypt function's output
As you've seen on the top is crypt function's output. I did the same thing 8 times, and crypt function has just given us different results about those.

If you want to learn more information about this subject, you can visit the PHP Manual web page: md5cryptsha1_filecrc32sha1hash

Friday, August 17, 2012

A nice video on RCaller 2.0


A nice video on RCaller is in Youtube now. The original link is in Quantlabs.net. Thanks for the uploader.

Wednesday, August 8, 2012

libjvm.so: cannot open shared object file: No such file or directory


In my Ubuntu Linux, I was trying to call Java from C++ using JNI. Compiling progress was succeed but at runtime I saw an error on concole:

libjvm.so: cannot open shared object file: No such file or directory

Finding the right solution took five seconds but it was quite easy. I modified the LD_LIBRARY_PATH environment variable using export command in the Linux shell:

export LD_LIBRARY_PATH=/usr/lib/jvm/default-java/jre/lib/i386:/usr/lib/jvm/default-java/jre/lib/i386/client

The location of JDK is always changed because of updates but Ubuntu stores the links of current JVM in default-java directory. It is /usr/lib/jvm/default-java in my Linux. Two directories must be added to LD_LIBRARY_PATH. The first one is jre/lib/i386 and the second one is jre/lib/i386/client or jre/lib/i386/server in default-java directory. Use of export solves my problem.

Good luck!


Monday, August 6, 2012

Online Interpreters and Compilers in codepad.org

Today, I stumbled upon a web page which has got an online interpreter/compiler interface for many languages including C, C++, D, Haskell, Lua, OCaml, Php, Perl, Python, Ruby, Scheme and Tcl.

Just write your code, select the corresponding language and hit the submit button.
You will be forwarded to an other page in which the output of your code is shown.

Click here to goto codepad.org. Have Fun!

Thursday, August 2, 2012

Fuzuli Android Application and Online Interpreter

We have just released the online interpreter and the Android application of Fuzuli, our programming language and interpreter.

You can simply run your Fuzuli programs using the site Fuzuli Online Interpreter. You will see a small hello world program. Since it only writes the "Hello world" string on the screen, it is not really relevant but makes sense. Every single programming language has its own Hello world! Type your program after deleting classical hello world program then click the RUN button. If your program is correct, you will see the output of your program at the bottom of the code. The other option for using our online interpreter is to download and install the Android application. You can download and install Fuzuli Online Interpreter for Android here. The file you will have found is ready to download and install. Do not forget to uninstall older versions if you have already installed one.

Have fun with Fuzuli!

Tuesday, July 31, 2012

Garbage Collection Mechanism of Fuzuli Interpreter

Fuzuli, our programming language and interpreter, has a garbage collection utility since its early stages. Garbage collection is an old term in computer science.

A chunk of memory is allocated for each software program by operating systems. Programs also allocate memory at runtime. Those programs are responsable to free the memory they allocated. Operations for allocating and freeing memory areas are performed using single commands such like malloc, free, new and delete in C and C++.

But allocating and freeing the chunks of memory is not that easy. When a reference to a dynamically created object is broken, the object remains suspended in the memory. Look at code below:


(let a (list 5 6 10 "Text"))
(let a NULL)

In the code above, a list of 5, 6, 10 and Text is created and referenced by the variable 'a'. Then, a is set to NULL. After all, what happened to list and its objects? The answer is easy. They suspended in the memory and waiting to be cleaned.

Ok, what about the code given below?


(let b 11)
(let a (list 5 6 10 b))
(let a NULL)


In the code above, a is linked to a list which contains 5,6,10 and b. b is an other variable which has a value of 11. After setting the value of 'a' to NULL, there is some garbage but this is a little bit different. Cleaning the object referenced by 'a' also means cleaning the object referenced by b. But we don't 'b' to be cleaned, it should stay alive. Reference Counting now comes into account. Counting references given to an object gives more information about the aliveness status of an object. In this example, the integer object has only one references in (let b 11).

When the code (let a (list 5 6 10 b)) runs; references of objects 5, 6, 10 and b increased by 1. The old reference count of b was 1, so b has a reference counting of 2. When (let a NULL) runs; reference counts of all objects contained by 'a' are decreased by 1. After all, the object which have reference count of 0 are deleted from the memory. The object 'b' is still alive!. Fuzuli uses this mechanism.

Garbage collecting in Fuzuli is automatic by default. Calling


(gc false)


simply disables the automatic garbage collector. Calling

(gc true)


enables the garbage collector. Whenever the garbage collector is enabled or disabled, it can be called manually. Simply calling (gc) triggers the garbage collector:

(let total (gc))
(print "Number of gargabe collected: " total "\n")


In the example below, a list of 1,2,...,1000000 created and referenced by a variable 'a'. Then a is set to NULL and generated garbage is collected manually.

(gc off)
(let limit 1000000)
(print "Creating array of 0..." limit "\n")
(let a (: 0 limit))
(print "Array created with length " (length a) "\n")
(dump)
(let a NULL)
(print "Gargabe Collecting manually:\n")
(gc)
(dump)


The output is

Creating array of 0...1000000
Array created with length 1000001
Environment Deep: 0
# Sub Environments: 0
# Tokens 1000054
Gargabe Collecting manually:
Environment Deep: 0
# Sub Environments: 0
# Tokens 67


 In the example above, there are 1000054 garbage objects before manual garbage collection. After garbage collecting, there are 67 objects which includes the source code itself. It was a nice experiment to implement a garbage collector in Fuzuli. Hope you have fun with it!

Sunday, July 29, 2012

How to Change Main/Start Screen on Android?

Hello! As you known, there is nothing to say about developing  and progressive Android all around the world. In this situation, we can find any idea to make application. Actually, this is not so easy :) Namely what I am trying to say is that Android provides us to create applications and be a developer in mobile world.

I am sure that most of us have played a game via our mobile phones. Things I said above were for any application actually. Because, games, software about educations, politics, health education, voluntariness, etc applications  allow Android skills.

If you want to create an application to be used by everyone (this is very assertive :) ), you have to be different than other apps. This difference should be about design, software or your idea. 

In this article, I'll show you some codes about tiny difference, "starting page" on your Android application.

I want to tell you about my mind. Users download your app and install it on the phone. The next step will be starting your application. This step is so important. Because, people who use the app decide how good the app is. For that reason, how to start the app should be very important for us. In this context, I can start to code about this.

I've got two classes: Main.java and startingPage.java

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.startingPagexml);
        
        Thread MyScreen = new Thread() {
         public void run() {
          try {
           sleep(5000);
     
           startActivity(new Intent(getApplicationContext(),startingPage.class));
          } catch (InterruptedException e) {
           e.printStackTrace();
          }
          finally {
           finish();
          }
         }
        };
        MyScreen.start();
    }


The code given above is the first page will be opened on the app. Thread "MyScreen" helps to go another page. When the app opened, wait 5 second and go to the startingPage.class. startingPage.class includes startingPagexml.xml Android Xml file. This file calls the page after 5 seconds.


public class acilis2 extends Activity {

 public void onCreate(Bundle savedInstanceState) {
  Toast.makeText(this, "Welcome to My Application", Toast.LENGTH_LONG).show();
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
 }


Toast.makeText(this, "Welcome to My Application", Toast.LENGTH_LONG).show();


This code introduces how to give user message after 5 second. If you want to see and learn more information about Toast notification, you can visit android developer official guide in here.


See you next article!

Thursday, July 19, 2012

Multithreading in Fuzuli Programming Language

Since our last commit, Fuzuli supports multithreading. This is the latest milestone that Fuzuli reached in revision tree of 0.1.x.

Fuzuli's multithreading capability stands on the well known boost threading library which will be a built-in package in next C++ standard.

Creating and running a thread in Fuzuli is easy. Define a function and create a thread for this function then call the thread_join method. The join method will wait until the function finishes its job. More than one threads can run at the same time in a time-sharing manner. Multithreading functions are stored thread.nfl, which is now a standard in Fuzuli API.

Lets give an example:


(require "/usr/lib/fuzuli/nfl/thread.nfl")

(function f (params)
 (block
  (print "F started\n")
  (foreach i in (: 1 10)
   (print "f\n")
   (thread_yield)
   (thread_sleep 100)
  )
  (return 0)
 )
)

(function g (params)
 (block
  (print "G started\n")
  (foreach i in (: 1 10)
   (print "g\n")
   (thread_yield)
   (thread_sleep 100)
  )
  (return 0)
 )
)

(function h (params)
 (block
  (print "H started\n")
  (foreach i in (: 1 10)
   (print "h\n")
   (thread_yield)
   (thread_sleep 100)
  )
  (return 0)
 )
)

(let t0 (thread "f"))
(let t1 (thread "h"))
(let t2 (thread "g"))

(thread_join t0)


In the example given above, we have three function f(), g() and h(). Those functions print messages "F started", "G started" and "H started" at the top of their bodies. A foreach loop then count from 1 to 10 and wait 100 milliseconds after each step. The output is shown below:

F started
H started
G started
g
h
f
g
h
f
g
h
f
g
h
f
g
h
f
f
g
h
f
h
g
g
f
h
g
h
f
f
g
h

Functions in this example run simultaneously. thread_join was called on t0, so whenever the function f() finishes its job, program ends. thread_yield is called for giving a chance to run to another threads. thread_sleep waits for given milliseconds if needed.That's all.


Sunday, June 17, 2012

Getting Contents of a DIV With PHP's DOM

Hi! Almost all of us use XML in our web sites. We can get contents with parsing XML files. But sometimes, we need another ways. The reason of this is that we want to get only one dom's content. For example an img element's content or it's value of id


Well, I will introduce how to get contents of element in this article. That's why I'll show you the sample given belown.


For my example, I got two files here:
  1. GetContent.php
  2. test.html
GetContent.php
<?php
$content="test.html";
$source=new DOMdocument();
$source->loadHTMLFile($content);
$path=new DOMXpath($source);
$dom=$path->query("*/div[@id='test']");
if (!$dom==0) {
   foreach ($dom as $dom) {
      print "<br>The Type of the element is: ". $dom->nodeName. "<br><b><pre><code>";
      $getContent = $dom->childNodes;
      foreach ($getContent as $attr) {
         print $attr->nodeValue. "</code></pre></b>";
      }
   }
}
?>
So, If you analyze the sample given above, you can see the point easily. The point is the content of div element which is id=test. The reason of existing test.html page is to get div's content.

test.html
<div id="test">This is my content</div>

What we have just seen up there, should be like on this demo page.

The Type of the element is: div
This is my content

The result is the text above. We'll see you guys next article!

Saturday, June 16, 2012

List Operations in Fuzuli Programming Language

Fuzuli, our new programming language and interpreter has several internal functions for list operations. Arrays are prominent objects of programming languages. Although many other programming languages use brackets for setting and getting values of array, this operator is not defined in Fuzuli. Lists are similar to Lisp's lists but they are different. As we said before, Fuzuli is neither a Lisp nor an Algol family, but it is something like a combination of them.
Any one dimensional Fuzuli list can be created using the list keyword. This keyword corresponds to internal ListExpression and can take infinite number of parameters to hold. An example for use of list keyword is given below:

(let a (list 12 3 4 5 "Hello" 5 4 2 10 2.13))

In the code above, a is list of elements 12, 3, 4, 5, "Hello", 5, 4, 2, 10, and 2.13, respectively. As we can see, the list a can hold elements from any type.

The keyword nth corresponds to the function nth for accessing elements using their indices. An example for use of nth is given below:

(let element (nth a 4))

The variable element now holds the value "Hello" because it has the indices of 4. Note that the index of first elements is zero. 4th element of list a can be changes as

(set a 4 "Fuzuli")

and variable a contains these elements:

12 3 4 5 "Fuzuli" 5 4 2 10 2.13


Lists can be constructed automatically in an increasing manner from an integer a to integer b. The code shown below is for creating a list from 1 to 1000:

(let biglist (: 1 1000))

 Ok! We borrowed this command from R because it is very nice and easy! Let's get the length of this list:

(let mylen (length biglist))

and mylen carries the value of 1000, the number of elements contained by biglist. One may need to append or prepend elements to lists. For those, we have append and prepend keywords for appending and prepending.

# Creating a list
(let mylist (list 1 2 3 4 5 6))

# Appending 7 to the end of mylist
(append mylist 7)

# Put a zero at the beginning
(prepend mylist 0)

# Print out the list
(print mylist)

The output is

[0, 1, 2, 3, 4, 5, 6, 7]

Well! How about removing elements? Lets remove the "4" from this list:

# Removing 4
(remove mylist 4)

The output is

[0, 1, 2, 3, 5, 6, 7]

There is also a find keyword for determining location of a given element in a list. Look at the code:

(let mylist (list "Jan" "Jun" "Aug" "Sep"))
(let index (find mylist "Jun"))
(print index)


The output is 1 because "Jun" has the index of 1 in array mylist.

There are extra functions in utils.nfl package for list operations. Those functions are not built-in but shipped within Fuzuli. Current utils.nfl package contains shuffle, sorta and sortb functions for mixing, ascending sorting and descending sorting of elements of a given list.

Another important point of Fuzuli lists is multi-dimensionality. We mentioned that Fuzuli lists can contain any type of objects. These object can exactly be an other list! And those list can take lists as their elements and so on... Let's create a 2x2 matrix of elements.

(let matrix
    (list
        (list 1 2)
        (list 3 4)
    )
)

(print matrix)

The output is


[[1, 2], [3, 4]]

The matrix given below has a dimension of 3x5:

(let matrix
    (list
        (list 1 2 3 4 5)
        (list 6 7 8 9 10)
        (list 11 12 13 14 15)
    )
)

(print matrix)

The output is

[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]

Accessing elements of multi-dimensional lists is easy! Follow the code:

(let matrix
    (list
        (list 1 2 3 4 5)
        (list 6 7 8 9 10)
        (list 11 12 13 14 15)
    )
)

(print (nth (nth matrix 0) 0) "\n")
(print (nth (nth matrix 1) 3) "\n")
(print (nth (nth matrix 2) 3) "\n")
(print (nth (nth matrix 2) 4) "\n")


The output is

1
9
14
15


becase matrix[0][0] is 1, matrix[1][3] is 9, matrix[2][3] is 14 and matrix[2][4] is 15 in C or Java notation.

Have fun with Fuzuli lists!







Sorting data with Fuzuli

In this article, I want to show how to sort data vectors using Bubble sort and Quick sort. Bubble sort is known to be one of the most in-efficient sorting algorithms. Quick sort has lower order of magnitude and it is known to be the most efficient one. There are tons of articles about these algorithms around the Internet and I don't want to give a detailed description and comparison of them.


Let me show how to write them in Fuzuli.



Bubble Sort in Fuzuli:


(def mylist LIST)
(let mylist (list 5 6 4 2 3 9 1 10 5))

(print "Original List:\n")
(print mylist "\n")

(for (let i 0) (< i (length mylist)) (inc i)
    (for (let j (clone i)) (< j (length mylist)) (inc j)
        (if (> (nth mylist i) (nth mylist j))
            (block
            (let temp (nth mylist i))
            (set mylist i (nth mylist j))
            (set mylist j temp)
            )
        )
    )
)

(print "After sorting:\n")
(print mylist "\n")


The output is :

Original List:
[5, 6, 4, 2, 3, 9, 1, 10, 5]

After sorting:
[1, 2, 3, 4, 5, 5, 6, 9, 10] 

 The code is similar to one written in both Lisp, C or Java! Hope the taste of code is good for you. Next one is the Quick sort:

Quick Sort in Fuzuli:


(def mylist LIST)
(let mylist (list 5 6 4 2 3 9 1 10 5))

(print "Original List:\n")
(print mylist "\n")



(function partition (params arr left right)
 (block
  (def i INTEGER) (def j INTEGER)(def tmp INTEGER)
  (def pivot INTEGER)
  (let i (clone left)) (let j (clone right))
  
  (let pivot (nth arr (/ (+ left right) 2)))
  

  (while (<= i  j)
   (block
             (while (< (nth arr i) pivot)(inc i))
                (while (> (nth arr j) pivot) (-- j)) 
       (if (<= i  j) 
     (block
            (let tmp  (nth arr i)) 
               (set arr i (nth arr j))
               (set arr j  tmp)
               (++ i)
               (-- j)
        )
    )
   )
  )
  (return i)
 )
)


(function quicksort (params arr left right) 
 (block
  (def index INTEGER)
  (let index (partition arr left right))
  (if (< left  (- index 1))
     (block
             (quicksort arr left  (- index 1))
   )
  )

       (if (< index right)
   (block
             (quicksort arr  index  right)
   )
  )
 )
)

(quicksort mylist 0 (- (length mylist) 1))
(print "After sorting:\n")
(print mylist "\n")


The output is :

Original List:
[5, 6, 4, 2, 3, 9, 1, 10, 5]

After sorting:
[1, 2, 3, 4, 5, 5, 6, 9, 10]

which is the same for bubble sort but the latter is faster.

Hope you like the code. See you next!

Friday, June 15, 2012

How to create dynagen network topology with multible dynamips service



I explained "Using dynagen & dynamips for multible cisco router simulation" in the http://stdioe.blogspot.com/2012/06/using-dynagen-dynamips-for-multible.html article before. I'm going to talk about how to create a dynagen configuration for multiple dynamips service. Also we are going to work about dynagen performance optimization. Let's create a network topology to try on our system.

Now, we have got three dynamips services. Each single dynamips service is creating three virtual routers and all of them are connected to each other. The first dynamips service contains R1, R2 and R3 routers, the second dynamips service contains R4, R5 and R6 routers, the third dynamips service contains R7, R8 and R9 routers. They are  seperated on configuration but logically they are connected to each other directly.

Start to practice,



1-) Starting dynamips services with different port numbers,

ismail@ismail-ThinkPad-T410:~$ dynamips -H 7200 &
ismail@ismail-ThinkPad-T410:~$ dynamips -H 7301 &
ismail@ismail-ThinkPad-T410:~$ dynamips -H 7402 &

2-) Create dynamips configuration file corresponding our network topology,

###############################1-Dynamips-1#############################
[localhost:7200]
  udp=10000
  workingdir = /tmp/workingdy1

[[3725]]
  image = /tmp/c3725-adventerprisek9-mz.124-15.T13.bin
  ram = 128
  #idlepc =  ?? # We will talk about this, later.
  ghostios = true
  sparsemem = true
  idlemax = 100 
  disk0=128

 [[Router R1]]
  model = 3725
  console = 2001
  autostart = false
  S0/0 = R2 S0/0

 [[Router R2]]
  model = 3725
  console = 2002
  autostart = false
  S0/0 = R1 S0/0
  S0/1 = R3 S0/0

 [[Router R3]]
  model = 3725
  console = 2003
  autostart = false
  WIC0/0 = WIC-2T
  S0/0 = R2 S0/1 
  S0/1 = R7 S0/1

###############################1-Dynamips-1#############################

###############################2-Dynamips-2#############################
[localhost:7201]
  udp=11000
  workingdir = /tmp/workingdy2

[[3725]]
  image = /tmp/c3725-adventerprisek9-mz.124-15.T13.bin
  ram = 128
  #idlepc =  ?? # We will talk about this, later.
  ghostios = true
  sparsemem = true
  idlemax = 100 
  disk0=128

 [[Router R4]]
  model = 3725
  console = 2004
  autostart = false
  S0/0 = R5 S0/0
  S0/1 = R8 S0/1

 [[Router R5]]
  model = 3725
  console = 2005
  autostart = false
  S0/0 = R4 S0/0
  S0/1 = R6 S0/0

 [[Router R6]]
  model = 3725
  console = 2006
  autostart = false
  S0/0 = R5 0/1

###############################2-Dynamips-2#############################

###############################3-Dynamips-3#############################
[localhost:7202]
  udp=12000
  workingdir = /tmp/workingdy3

[[3725]]
  image = /tmp/c3725-adventerprisek9-mz.124-15.T13.bin
  ram = 128
  #idlepc =  ?? # We will talk about this, later.
  ghostios = true
  sparsemem = true
  idlemax = 100 
  disk0=128

 [[Router R7]]
  model = 3725
  console = 2007
  autostart = false
  S0/0 = R9 S0/0
  S0/1 = R3 S0/1

 [[Router R8]]
  model = 3725
  console = 2008
  autostart = false
  WIC0/0 = WIC-2T
  S0/0 = R9 S0/1
  S0/1 = R4 S0/1

 [[Router R9]]
  model = 3725
  console = 2009
  autostart = false
  S0/0 = R7 0/0
  S0/1 = R8 0/0

###############################3-Dynamips-3#############################

I saved the content above with a file name of sample2.net name in /tmp directory.  We need working directories as below:

ismail@ismail-ThinkPad-T410:~$ mkdir /tmp/workingdy1
ismail@ismail-ThinkPad-T410:~$ mkdir /tmp/workingdy2
ismail@ismail-ThinkPad-T410:~$ mkdir /tmp/workingdy3

3-) The working directories are ready. Right now, dynagen service is ready to start. I did a mistake to shown follow up how to troubleshooting.

ismail@ismail-ThinkPad-T410:~$ dynagen /tmp/sample2.net 
Reading configuration file...

Shutdown in progress...
Shutdown completed.
Shutdown in progress...
Shutdown completed.
Shutdown in progress...
Shutdown completed.
*** Warning:  Connecting R6 S0/0 to R5 0/1 resulted in:
 malformed destination interface: R5 0/1
*** Warning:  Connecting R9 S0/0 to R7 0/0 resulted in:
 malformed destination interface: R7 0/0
*** Warning:  Connecting R9 S0/1 to R8 0/0 resulted in:
 malformed destination interface: R8 0/0

*** Error:  errors during loading of the topology file, please correct them
Shutdown in progress...
Error: could not communicate with dynamips server localhost
It may have crashed. Check the dynamips server output.
Exiting...
Press ENTER to exit
[3]+  Segmentation fault      (core dumped) dynamips -H 7202
ismail@ismail-ThinkPad-T410:~$ 

Normally, you can define a connection on both ends of lines. But on our sample, dynagen service doesn't accept this duplicate defination. I removed " S0/1 = R6 S0/0" line in R5 router part. Also "  S0/0 = R9 S0/0" line in R7 part and " S0/0 = R9 S0/1" line in R8 part. After editing, sample2.net file has a content as seen below:


###############################1-Dynamips-1#############################
[localhost:7200]
  udp=10000
  workingdir = /tmp/workingdy1

[[3725]]
  image = /tmp/c3725-adventerprisek9-mz.124-15.T13.bin
  ram = 128
  #idlepc =  ?? # We will talk about this, later.
  ghostios = true
  sparsemem = true
  idlemax = 100
  disk0=128

 [[Router R1]]
  model = 3725
  console = 2001
  autostart = false
  S0/0 = R2 S0/0

 [[Router R2]]
  model = 3725
  console = 2002
  autostart = false
  #S0/0 = R1 S0/0
  S0/1 = R3 S0/0

 [[Router R3]]
  model = 3725
  console = 2003
  autostart = false
  #S0/0 = R2 S0/1
  S0/1 = R7 S0/1

###############################1-Dynamips-1#############################

###############################2-Dynamips-2#############################
[localhost:7201]
  udp=11000
  workingdir = /tmp/workingdy2

[[3725]]
  image = /tmp/c3725-adventerprisek9-mz.124-15.T13.bin
  ram = 128
  #idlepc =  ?? # We will talk about this, later.
  ghostios = true
  sparsemem = true
  idlemax = 100
  disk0=128

 [[Router R4]]
  model = 3725
  console = 2004
  autostart = false
  S0/0 = R5 S0/0
  S0/1 = R8 S0/1

 [[Router R5]]
  model = 3725
  console = 2005
  autostart = false
  #S0/0 = R4 S0/0
  S0/1 = R6 S0/0

 [[Router R6]]
  model = 3725
  console = 2006
  autostart = false
#  S0/0 = R5 0/1

###############################2-Dynamips-2#############################

###############################3-Dynamips-3#############################
[localhost:7202]
  udp=12000
  workingdir = /tmp/workingdy3

[[3725]]
  image = /tmp/c3725-adventerprisek9-mz.124-15.T13.bin
  ram = 128
  #idlepc =  ?? # We will talk about this, later.
  ghostios = true
  sparsemem = true
  idlemax = 100
  disk0=128

 [[Router R7]]
  model = 3725
  console = 2007
  autostart = false
  S0/0 = R9 S0/0
  #S0/1 = R3 S0/1

 [[Router R8]]
  model = 3725
  console = 2008
  autostart = false
  S0/0 = R9 S0/1
  #S0/1 = R4 S0/1

 [[Router R9]]
  model = 3725
  console = 2009
  autostart = false
#  S0/0 = R7 0/0
#  S0/1 = R8 0/0

###############################3-Dynamips-3#############################

We already started dynamips with 7200, 7201 and 7202 ports but dynagen service has been crashed. Some dynamips services may have been crashed. We have to check them before restarting dynages service.

ismail@ismail-ThinkPad-T410:~$ ps -ef | grep dynamips
ismail    3811  3756  1 10:15 pts/0    00:00:14 dynamips -H 7200
ismail    3829  3756  1 10:16 pts/0    00:00:14 dynamips -H 7201
ismail    4017  3756  0 10:27 pts/0    00:00:00 grep --color=auto dynamips

So One dynamips service crashed and other two ones still working. I want to kill all dynamips services and start them again to make sure about everything on the way. We can kill a PID using the "kill -9 3811" command but I selected pkill command in this sample to show first practice.

ismail@ismail-ThinkPad-T410:~$ pkill dynamips
[1]-  Terminated              dynamips -H 7200
[2]+  Terminated              dynamips -H 7201
ismail@ismail-ThinkPad-T410:~$ 

And now, there is no any running dynamip process. We can start all of them again,

ismail@ismail-ThinkPad-T410:~$ dynamips -H 7201 &
ismail@ismail-ThinkPad-T410:~$ dynamips -H 7202 &
ismail@ismail-ThinkPad-T410:~$ dynamips -H 7203 &
ismail@ismail-ThinkPad-T410:~$ dynagen /tmp/sample2.net 
Reading configuration file...
...
...
...
Dynagen management console for Dynamips and Pemuwrapper 0.11.0
Copyright (c) 2005-2007 Greg Anuzelli, contributions Pavel Skovajsa

=> 

Finally dynagen loaded our network topology. We can handle it now. We can start routers with "start" command on dynagen console and get console of routers with "telnet Rx" command (x is number of router name, for example R4).

We may need to use the "idlepc" parameter in this sample. If you need more performance, you have to use idlepc parameter. Dynagen can optimize itself using the value given for idlepc. We have to learn only what is our idlepc value for our system. We can use following command in the dynagen console,

=> start R1
=> idlepc get R1
Please wait while gathering statistics...

Please wait while gathering statistics...
Done. Suggested idling PC:
   0x60c08128 (count=22)
   0x60c08164 (count=33)
   0x60c08180 (count=35)
   0x60c081c0 (count=66)
   0x62b2823c (count=45)
   0x60c08bf8 (count=23)
   0x60c08c20 (count=20)
   0x614b0e34 (count=38)
   0x62b2b134 (count=20)
   0x6026bca4 (count=30)
Restart the emulator with "--idle-pc=0x60c08128" (for example)
   1: 0x60c08128 [22]
   2: 0x60c08164 [33]
   3: 0x60c08180 [35]
   4: 0x60c081c0 [66]
   5: 0x62b2823c [45]
   6: 0x60c08bf8 [23]
   7: 0x60c08c20 [20]
   8: 0x614b0e34 [38]
   9: 0x62b2b134 [20]
  10: 0x6026bca4 [30]
Potentially better idlepc values marked with "*"
Enter the number of the idlepc value to apply [1-10] or ENTER for no change: 
No changes made
=> 

If you find any "*" line, you can use this line value. If you don't have any marked line with "*", you can try to get idlepc value again.

Thursday, June 14, 2012

Calculating Levenshtein Distance Between Two Strings in Fuzuli

Hi! I am so happy I can code with Fuzuli programming language. In this article, I'll show you how to calculate the distance between two strings on Fuzuli. I usually use Levenshtein distance on PHP. This situation is the same on Fuzuli. Before introducing my sample, sharing the Levenshtein function would be nice, I think.






For this article, I've got an example here: 
The code given belown is about how to calculate the distance between strings. 

(require "nfl/io.nfl")
(require "nfl/string.nfl")

(print "Please enter a word for calculating distance: ")
(let word(readline))

(let Array (list "windows" "ubuntu" "android"))

(foreach i in Array
   (block
  (let distance (levenshtein word i))
  (print distance " for " i "\n")
    )
)

(require "nfl/string.nfl")
(require "nfl/io.nfl")


The code shown above shows how we import a required package. string package is for Levenshtein function, namely it is not "fuzuli" :) io package is for readline.


You can run it by typing:

fuzuli levenshtein.fzl
Screen View
Screen View
If you compare screen views, you can see the differency. First, I wrote "fuzuli" and the system has found distances, but when I write "android", the system has found zero distance for "android".


Here, I actually wanted to show you many things. One of'em was how to get a piece of array with foreach. Other one was the point of this article, Levenshtein function. I hope that was enough and helpful for you!


See you!

Calculating roots of a parabola with Fuzuli Programming Language

Fuzuli has its core libraries inhereted from C++ standard libraries. That is why adapting to Fuzuli does not require climbing a sharp learning curve. Only the requirement is to have a habitat of parenthesis syntax.

In this article, we write a small script for calculating roots of a parabola. This script includes two Fuzuli packages, io and math. This packages are required for readline, exit and sqrt functions. The remaining part of this script uses the internal functions of Fuzuli.

A parabola is a function in form of ax^2 + bx + c where a!=0. Delta, which is calculated as b^2 - 4ac is an indicator of number of real roots. If delta is less than zero, the parabola has no real roots. If delta is zero, all of the roots shares the same value. If delta is greater than zero, there are two distinct roots. This is not our subject now and it is well described at the Wikipedia.

Before coding, you can manually install the Fuzuli for Linux or Windows systems. Please visit the Fuzuli Official Web Page and Google Code page for installing instructions.
Our Fuzuli script is shown below:


(require "/usr/lib/fuzuli/nfl/io.nfl")
(require "/usr/lib/fuzuli/nfl/math.nfl")

(print "Please enter a b and c for parabola ax^2 + bx + c\n")
(print "Enter a:")
(let a (readline))

(print "Enter b:")
(let b (readline))


(print "Enter c:")
(let c (readline))

(let delta (- (pow b 2) (* 4 (* a c))))
(print "Delta is " delta "\n")

(if (< delta 0.0)
 (block
  (print "No real roots exist\n")
  (exit 0)
 )
)

(if (= delta 0.0)
 (print "There are two equal roots\n")
)

(if (> delta 0.0)
 (print "There are two different real roots\n")
)

(let x1 (/ (+ (* -1 b) (sqrt delta)) (* 2 a)))
(let x2 (/ (- (* -1 b) (sqrt delta)) (* 2 a)))
(print "x1=" x1 " and x2=" x2 "\n")
I write the codes above in the file "delta.fzl". You can run it by typing

#fuzuli delta.fzl


and program asks for values of a, b and c. The output screen is similar to the output given below:


Have fun with Fuzuli!

Wednesday, June 13, 2012

Extracting links from web pages using Fuzuli

We have too much written about Fuzuli and its core components but we didn't publish any real world applications run on it.

Fuzuli, our new general purpose programming language and interpreter, is first introduced in Practical Code Solutions blog and has the official web page http://www.fuzuliproject.org.

Here we have an example of extracting links from an HTTP connection. Program asks for a domain name. The default one is amazon.com and processed by just pressing enter key. Then program sends an HTTP GET request to the server and reads the content. After collecting all of the content, program starts to parse HTML codes and shows the tags start with an A tag.  The Fuzuli code is shown below:


# Loading required packages
(require "/usr/lib/fuzuli/nfl/io.nfl")
(require "/usr/lib/fuzuli/nfl/string.nfl")
(require "/usr/lib/fuzuli/nfl/net.nfl")

# Getting a domain name from user.
(puts "Please give a domain (for default just type enter):")
(let word (readline))

# If user did not type anything
# set the default page to amazon.com
(if (< (strlen word) 3)
   (let word "amazon.com")
)
(print "Doing " word "\n")


# Open a socket connection to host
(print "Connecting " word "\n")
(let socket (fsockopen word 80))

# Sending HTTP Request
(print "Sending request\n")
(fsockwrite socket (strcat (list "GET /\n\n")))

# Reading html content
(print "Retrieving result\n")
(def htmllist LIST)
(while 1
   (let c (fsockread socket 1))
   (if (= (typeof c) NULL) (break))
   (append htmllist c)
)
# Closing socket
(fsockclose socket)

(print "Constucting string\n")

(let html (strcat htmllist))
(let len (strlen html))
(print len " bytes read.\n")

(def part STRING)
(def i INTEGER)

# Parsing loaded content
(for (let i 0) (< i len) (inc i)
   (let part (substr html i (+ i 7)))
   (if (= part "<a href")
      (block
         (print "link found: \n")
         (while (!= part "</a>")
            (let part (substr html i (+ i 4)))
            (print (substr html i (+ i 1)))
            (inc i)
         )
         (print part "\n")
      )
   )
) 


The example given above combines variable definitions and scopes, loops, sockets and basic io. Please get more detailed information about the keywords, commands and functions using Fuzuli's documentation site.

PHP and Microsoft Access Database Connection

We all know that MySQL database connection is the best way for PHP. This make us so strong during coding. But what I have to say is that is not the only way. We have some opinions about connecting to databases. These may be between PHP&Access, PHP&Sqlite and PHP&PostgreSQL etc. But here, we interested in the first one, PHP&Access.

Access is one of the most popular databases in the world. It was made by Microsoft Corporation. You can find here more information about Access. A person who uses the Access can create, update, delete, etc tables on databases without using SQL.  That's why we can see easily how important  the interface is. In this respect this is so simple and useful.


An Example on Access : Getting data from access


<?php
$conn = new COM("ADODB.Connection") or die("ADODB Oops!");
$conn->Open("DRIVER={Microsoft Access Driver (*.mdb)};DBQ=C:\Users\UserName\Desktop\ MyDatabaseFile .mdb");
$data = $conn->Execute("SELECT * FROM myTable ORDER BY users ASC");

print "<TABLE border='1'><TR><TD colspan='6'>DATA</TD><TR>";
while (!$data->EOF)
{
print "<tr>";
print "<td>" . $ data ->Fields[0]->value . " </td>";
print "<td>" . $ data ->Fields[1]->value . " </td>";
print "</tr>";
$ data ->MoveNext();
}
echo "</TABLE>";


Just save code above as access.php and run it. It's going to be like the screen belown.
Screen View
If you try to figure that out, codes belown will be helpful for you.

$conn = new COM("ADODB.Connection") or die("ADODB Opps!");
$conn->Open("DRIVER={Microsoft Access Driver (*.mdb)};DBQ=C:\Users\UserName\Desktop\MyDatabaseFile.mdb");

We try to connect access database with php here.

odbc_connect(‘dsn name’, ‘user name’, ‘password’);

There is a problem with this! When you look at the code belown, can realize user_name and password field. What are these ones? How can we build on these? That's the point on this article actually. Just go to the localhost and this page:

phpinfo.php


<?php
Phpinfo();
?>



When run phpinfo.php file, need look into ODBC properties

ODBC with phpinfo.php
You must implement your user name and password for working on it. By the way, it is easier to make this operations with codes. That's why i show you as code, not screen views.

Well, let's code then :)

$conn = new COM("ADODB.Connection") or die("ADODB Opps!");
$conn->Open("DRIVER={Microsoft Access Driver (*.mdb)};DBQ=C:\Users\UserName\Desktop\MyDatabaseFile.mdb");

$data = $conn->Execute("SELECT * FROM myTable ORDER BY users ASC");

print "<TABLE border='1'><TR><TD colspan='6'>DATA</TD><TR>";
while (!$data->EOF)
{
print "<tr>";
print "<td>" . $ data ->Fields[0]->value . " </td>";
print "<td>" . $ data ->Fields[1]->value . " </td>";
print "</tr>";
$ data ->MoveNext();
}
echo "</TABLE>";

This is my result page with php, html and sql.

See you guys next article!