Saturday, June 2, 2012

Mapped IP configuration on Netscreen



         I'm going to talking about MIP feature on Nescreen via a sample network design. This network uses private addresses in the Internal Side and has got public addresses to use external side. The network structure is shown below,


         As shown on network design, we have a computer which has got 172.16.100.11 ip address and we want to map it to 21x.xxx.xx.236 public IP address. What we want is shown below:

         When computer sends any request to public Internet side, devices which are located on Internet side will see it as 21x.xxx.xx.236 and when a request is sent from Internet to 21x.xxx.xx.236 IP address, FW redirects it to 172.16.100.11 IP address. So 172.16.100.11 means 21x.xxx.xx.236 and 21x.xxx.xx.236 means 172.16.100.11.

We will set MIP configuration on Netscreen for this purpose.

(The external side is defined as Internet zone and the internal network is defined as system zone on firewall before. Following configurations are illustrating as that zone names)

         First of all, 21x.xxx.xx.236 is an IP address which is located in the segment between FW and Main router. This segment is not behind of a firewall, conversely, front of the firewall. The firewall should be taken on itself like a sub-interface. Anyway we have to see 21x.xxx.xx.236 IP address in the main router ARP Table with a MAC address which is got from firewall. Otherwise, packages which contains 21x.xxx.xx.236 in the destination field is not able to arrive to target. I will explain this background info at the end of this article. Let's continue to configuration.

1)
         Select “Interfaces” item on the menu which is located on left side of the netscreen configuration web-interface.


2) 
         When Interfaces item is clicked, we can see a page as shown below on the right side of page.


3)
         Clicking to Edit link which is marked on above picture. When It is clicked, following page will be opened.


4)
         Clicking to MIP link, this page is listing already created MIPs.


5)
         Clicking to New button on the right side.


6)
         When clicking to OK and check MIP list again, we will see our configuration on the MIP list,



7)
         Right now, Mapped IP configuration is done. But we have to create the policy to permit traffic. It should have both directions. The following one is about Internet to system direction.


         When you are clicking to policies under the policy menu, you can see policy list on the right side of the page. There are “from” and “to” commands at top of the right side. Select the “Internet” option from the combobox “from” and select system using the “to” part.  


         Right now, The firewall is listing policies from internet to system. Clicking to “New” buttom on the top-right side.

         These two points are important at this step. First, destination address should be MIP. Second, action should be “Permit”.

8)
         Select “system” for 'from' part and select “Internet” for 'to' part on top side and click “go” button after than click to “New” button.


         Source address should be 172.16.100.11 and destination address should be “any”. Than select permit for action.  

         This step permits access to Internet side for 172.16.100.11 addressed computer. If you want to permit access from internet to your internal workstation only, you don't need this step.  


Let's analyse communication background on this scenario.

Telnet to Main router (It's Cisco 3661) and run “show arp” command. Getting output like below,

UGC_Topkapi_3661#show arp
Protocol  Address          Age (min)  Hardware Addr   Type   Interface
..
Internet  21x.xxx.xx.250          0   0010.dbff.22e0  ARPA   FastEthernet4/0
….
Internet  21x.xxx.xx.236        161   0010.dbff.22e0  ARPA   FastEthernet4/0
…
...


As you know, 21x.xxx.xx.236 and 21x.xxx.xx.250 ip addresses has got exactly same MAC address. The Main router should be send 21.x.xxx.xx.236 packages to firewall mac. The firewall know already how to access to main router. If you understand any step, let me know please.

Compiling Happycoders libsocket in Ubuntu


 Happycoders libsocket is an object oriented and platform independent socket library for C++. It has a nice structure for both tcp and udp sockets. It runs like a charm if you want to connect a server and get the content as well as listen from a port and accept the connections.

Since package maintainers published a debian package mainly for Debian and Ubuntu distros, it can easly be installed on those systems. If you use another os the solutions is to compile it yourself. However, GCC throws an error message which can be easily solved. In order to compile the package and use it with your C++ applications, first open an console and type


wget http://www.speedblue.org/conf/libsocket-1.8.tar.gz


so we have the source package downloaded. Extract the tar archive

gunzip libsocket-1.8.tar.gz
tar -xvf libsocket-1.8.tar 


Now we have a folder with a name of libsocket-1.8. Get in this folder and start the compilation process:

./configure


and then type

make


After getting some output, GCC throws an error:

make  all-recursive
make[1]: Entering directory `/tmp/socket/libsocket-1.8'
Making all in src
make[2]: Entering directory `/tmp/socket/libsocket-1.8/src'
Making all in tests
make[3]: Entering directory `/tmp/socket/libsocket-1.8/src/tests'
make[3]: Nothing to be done for `all'.
make[3]: Leaving directory `/tmp/socket/libsocket-1.8/src/tests'
make[3]: Entering directory `/tmp/socket/libsocket-1.8/src'
if /bin/bash ../libtool --mode=compile g++ -DHAVE_CONFIG_H -I. -I. -I.. -I../src    -g -O2 -Wall -ansi -pedantic -MT socket.lo -MD -MP -MF ".deps/socket.Tpo" \
   -c -o socket.lo `test -f 'socket.cc' || echo './'`socket.cc; \
 then mv -f ".deps/socket.Tpo" ".deps/socket.Plo"; \
 else rm -f ".deps/socket.Tpo"; exit 1; \
 fi
 g++ -DHAVE_CONFIG_H -I. -I. -I.. -I../src -g -O2 -Wall -ansi -pedantic -MT socket.lo -MD -MP -MF .deps/socket.Tpo -c socket.cc  -fPIC -DPIC -o .libs/socket.o
socket.cc: In member function 'void Network::Socket::_write_str_bin(int, const string&) const':
socket.cc:238:44: error: 'memcpy' was not declared in this scope
make[3]: *** [socket.lo] Error 1
make[3]: Leaving directory `/tmp/socket/libsocket-1.8/src'
make[2]: *** [all-recursive] Error 1
make[2]: Leaving directory `/tmp/socket/libsocket-1.8/src'
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory `/tmp/socket/libsocket-1.8'
make: *** [all] Error 2


When you look into to error message we can see the key point:

socket.cc: In member function 'void Network::Socket::_write_str_bin(int, const string&) const':
socket.cc:238:44: error: 'memcpy' was not declared in this scope


It is clear that, GCC needs memcpy to be declared before it is used. It is a function defined in the standar C package string.h and it cstring in C++. Simply open the socket.cc and add the line

#include <string.h>


and compile again. After typing the make command you will get a new error message. A part of this error message is given below:

udpsocket.cc: In member function 'virtual std::string Network::UdpSocket::_read_line_bin(int, unsigned int)':
udpsocket.cc:68:29: error: 'memset' was not declared in this scope


and this is a similar error. memset is an other standard function defined in string.h in C++ and C. Simple edit the file udpsocket and add the same header

#include <string.h>


After compiling many times, GCC will throw similar errors. To cope with this
  • Include string.h in socket.cc
  • Include string.h in udpsocket.cc
  • Include string.h in tcpsocket.cc
  • Include string.h and stddef.h in localsocket.cc
  • Include string.h in netsocket.cc
After all, we you type make again, GCC compiles and produces binary outputs. Then type

sudo make install


if you want to install. Happycoders socket library is a static library by default and your application will not depent it externally. Have fun!

Friday, June 1, 2012

Installing Fuzuli on Ubuntu 12.04 LTS


Following pictures are explaining how to install Fuzuli on Ubuntu 12.04 LTS using the DEB package given in http://code.google.com/p/fuzuli/downloads/list









Thursday, May 31, 2012

Mathematics with Fuzuli

Our new general purpose interpreter and language Fuzuli was first introduced in Practical Code Solutions and has the official web page in FuzuliProject.org.

Fuzuli has several packages which are mostly wrappers of C++ libraries. One of them is the math package. It is math.nfl and stated in /usr/lib/fuzuli/nfl in Linux installations by default.

The math.nfl package simple wraps some basic mathematical functions such as square root, exponential, logarithms, floor, ceil and round as well as trigonometric functions such as sin, cos, tan, atan, acos, etc. These functions are directly inherited from the standard C++ library.  A list of functions in the math.nfl package is shown below:


FunctionDescriptionExampleResult
PIReturns a short presentation of PI
(let a (sin (/ PI 2)))
1.0
sinReturns sin of a given reference
(let a (sin 0))
0.0
cosReturns cos of a given reference
(let a (cos 0))
1.0
tanReturns tan of a given reference
(print (tan 1))
1.55741
absReturns absolute value
(print (abs -5))
5
sqrtReturns square root
(print (sqrt 25))
5
expReturns E^x
(print (exp 1))
2.71828
logReturns natural logarithm
(print (log (exp 1)))
1.0
log10Returns logarithm in base 10
(print (log10 10))
1.0
log2Returns logarithm in base 2
(print (log2 2))
1.0
coshReturns hyperbolic cos
(cosh x)
sinhReturns hyperbolic sin
(sinh x)
tanhReturns hyperbolic tan
(tanh x)
asinReturns inverse sine
(asin 1)
acosReturns inverse cosine
(acos 0)
atanReturns inverse tangent
(atan 1.55741)
1
atan2Two arguments arctan function
(atan2 1 1)
0.7853981634
powReturns a^x
(print (pow 5 2))
25
ceilReturns ceil of a given reference
(print (ceil 2.3))
3.0
floorReturns floor of a given reference
(print (floor 2.3))
2.0
roundReturns round of a given reference. (nearest integer)
(print (round 2.3))
2.0
isinfReturns 1 if the given reference is either negative or positive infinitive else returns 0
(print (isinf (/ 19 0)))
1


The table shown above is hopefully enough to introduce our functions in the math package. Any Fuzuli program should include the math package using the (require) expression if any math function shown above is planned to use. Look at the code below:


(require "/usr/lib/fuzuli/nfl/math.nfl")
(print (isinf (/ 19 0)))


Although math functions are collected in an external package, Fuzuli supports built-in arithmetic functions. The code shown below is calculating ordinary least squares regression coefficients. As you see, no math functions required and only the arithmetic functions are used.

(let x (list 1 2 3 4 5 6 7 8 9 10))
(let y (list 10 20 30 40 50 60 70 80 90 100))

(function sum (params a)
 (block
  (def s FLOAT)
  (def i INTEGER)
  (let s 0.0)
  (for (let i 0) (< i (length a)) (inc i)
   (let s (+ s (nth a i)))
  )
  (return s)
 )
)

(function mean (params a)
 (block 
  (def total FLOAT)
  (def result FLOAT)

  (let total (sum a))
  (let result (/ total (length a)))
   
  (return result)
 )
)


(function covariance (params c d)
 (block
  (def meana FLOAT)
  (def meanb FLOAT)
  (def xy FLOAT)
  (def i INTEGER)
  (let meana (mean c)) 
  (let meanb (mean d))
  (let xy 0.0)
  (for (let i 0) (< i (length a)) (inc i)
   (block
    (let xy (+ xy (* (- (nth c i) meana) (- (nth d i) meanb ))))
   )
  ) 
  (return xy)
 )

)


(let beta1 (/ (covariance x y) (covariance x x)))
(let beta0 (- (mean y) (* beta1 (mean x))))
(print "beta0 " beta0  "\n") 
(print "beta1 " beta1  "\n")


The result is 0.0 for beta0 and 10.0 for beta1.

See you in next entry. Have fun!

Wednesday, May 30, 2012

Defining variables and variable scopes in Fuzuli



Fuzuli has a basic variable scoping strategy and it is easy to understand. Many Algol family languages support variable types, variable defining, initial value setting and updating values. Internally, everything in Fuzuli is a Token. A Token is a C++ object. It can hold an INTEGER, a FLOAT, a STRING, a LIST of all types and a COBJECT. Variables are basically type of an INTEGER, a FLOAT or a STRING. A Fuzuli LIST is a vector or array of those kind of objects. A LIST may be a member of an other LIST. So, objects in Fuzuli can be recursively deep. A COBJECT is a (void*) pointer and can be anything. This type of variable is used for external function calls, usually from C++ or C libraries such as Math, IO and MySQL. Integration of COBJECT types expands the universe that Fuzuli can access. However, a standard user does not need this kind of object because Nafile (nfl) packages wrap those external function calls.

We use (let) expression to set value of a variable in Fuzuli:


# Value of a is set to 10
(let a 10)

# a is now 20
(let a 20)

# a is now a string
(let a "Hello!")

# a is now a double precision number
(let a 3.141592)


(block) expression defines a block in which variables are locally scoped. If a variable defined in a higher scope, it is current in the child scope. In other terms, if a variable set in a deeper scope but it is first defined in the higher scope, the first defined variable is current. Have a look at the example below:


# Value of a is set to 10
# a is defined in higher level
(let a 10)

# this block defines a deeper (local) scope
(block
  (let a 20)
)

# out of the block, a is 20 because global a is accessed from the local scope
(print a)
# the answer is 20


However, one can want to define a local variable with same name of the higher scoped variable. For this, (def) expressions can be used. Look at the example below:

# Defined in an higher scope
(let a 10)

# deeper scope
(block
  (def a NULL)
  (let a 7)
)

# we are in higher scope again
(print a)
# the answer is 10.


So, in Fuzuli, a user does not need to define variables if they want to give a reference them. Look at the (for) expression given below:

(let i 5)

(for (let i 0) (< i 10) (inc i)
    (block
        (print "i is " i "\n")
    )
)

(print "Finally, i is " i  "\n")


The output is

i is 0
i is 1
i is 2
i is 3
i is 4
i is 5
i is 6
i is 7
i is 8
i is 9
Finally, i is 10


because, i is first defined in a higher level of scope. If i is not defined before the (for) expression, the code should be like this

(for (let i 0) (< i 10) (inc i)
    (block
        (print "i is " i "\n")
    )
)

(print "Finally, i is " i  "\n")


and the output is

i is 0
i is 1
i is 2
i is 3
i is 4
i is 5
i is 6
i is 7
i is 8
i is 9
Finally, i is NULL


because i is defined locally and it is invisible in the higher scope. Strategy of variable scoping in function calls is an other special issue in Fuzuli Suppose that we have an (sum) function defined as follows:

(function sum (params x)
    (block
        (def t FLOAT)(def i FLOAT)
        (let t 0.0)
        (foreach i in x
            (let t (+ t i))
        )
        (return t)
    )
)


In the example above, the (sum) function takes a list 'x' as parameter and returns the sum of elements of this list. The variable 't' is defined and set in the function body. This is unnecessary if we don't use a variable with name 't' in the higher level of scopes. For convenience and security, defining all local function variables before they were used is a good habit. For the rest of the example, the sum function can be called using

(let mylist (list 1 2 3 4 5))
(let result (sum mylist))
(print result "\n")
and gives the result of 15. Hope you have fun !

An informative video on RCaller

Somebody on the Internet submitted an informative video on how to use RCaller for calling R from withing Java applications in YouTube.

It is nice to see RCaller has an higher usage rates after its 2.0 version.

You can see the embedded video in this entry. Have a nice training!

Writing CGI scripts with Fuzuli Programming Language

Fuzuli is also suitable for writing CGI (Common Gateway Interface) scripts. The logic underlying the CGI script is to define a content type for the document and print out the content using the standard input & output routines. Form elements posted by a client are generally handled using some environmental variables and standard input. Handling those variables varies according to the sending method of html forms.

Fuzuli has a different approach for CGI scripts. For example, in Php, a script file has a file extension of .php and it must be started with some html tags or a php starter

<?php

tag. While the file extension is .php, we have to declare that "we have finished writing html codes and now we are starting a new php area!". However, in Fuzuli, the default behavior is to write fuzuli code and writing html is an exception.

A fuzuli cgi script must define the location of the interpreter in the top level of the code:

#!/usr/bin/fuzuli

Secondly, before writing any output, content-type should be defined :


#!/usr/bin/fuzuli
(print "Content-type: text/html\n\n")


Ok. That is too much naive to CGI scripters. How to add html tags to this script? Follow the example below:

#!/usr/bin/fuzuli
(print "Content-type: text/html\n\n")
<?html

<h1>Hello World!</h1>

?>


Very nice, hah? So we can easily combine our logic and html! Ok lets do some html forms and handle them in Fuzuli.


#!/usr/lib/fuzuli/fuzuli
(print "Content-type: text/html\n\n")

<?html
   <form method="get">
   Enter your name:
   <input type="text" name="name">
   <input type="text" name="email">
   <input type="submit" value="Click">
</form>
?>

(let name (REQUEST "name"))
(let email (REQUEST "email"))

(if (isset name)
    (print "Posted name is : " name)
)

<?html
<h1>-----------------</h1>
?>

(if (isset email)
    (print "Posted email is: " email)
)



In the example above, the name and the email variables are sent from the html form. If they are set, their values are printed. Very simple. A Fuzuli loop can include an html block so one can generate html codes efficiently. Look at the code below:

#!/usr/lib/fuzuli/fuzuli

(print "Content-type: text/html\n\n")

<?html
<table border = "1">
?>

(let days 
  (list "sunday" 
        "monday" 
        "tuesday" 
        "wednesday"
        "thursday" 
        "friday" 
        "saturday"
   )
)
(for (let i 0) (< i (length days)) (inc i)
    (block
            <?html <tr><td><b> ?>

            (print i)

            <?html </b></td>

            <td><i>
            ?>

            (print (nth days i))


            <?html
                </b></td></tr>
            ?>
    )
)

<?html
</table>
?>      


Fuzuli supports cookie operations internally. setcookie and getcookie functions were implemented for setting and getting cookies, respectively. Note that cookies must be set before sending the content-type header.

setcookie (var "This is cookie value")
(let value (getcookie "var"))


The next step is to implement session functions. We are still discussing the session structure of Fuzuli. It seems it is the most convenient method to implement this functionality in Nafile (nfl) packages. Hope you like scripting with Fuzuli...

Friday, May 25, 2012

Fuzuliproject.org

After publishing Fuzuli's source code and introductory blog entries, we have just published our web site, official Fuzuli home page. We hope you can easly follow up the news about our interpreter using this site.

Follow our news and us!

For the stdioe team, A.Gokhan Satman.

Thursday, May 24, 2012

File operations in Fuzuli

Fuzuli, our new programming language and interpreter, was first introduced in Fuzuli: A new general purpose interpreter and language has several input and output functions completely derived from standard C and C++.

Since our language is in its first stages and input and output functions have high priority, Fuzuli has adequate number of functions for those jobs.

First of all, the io package must be included before any function call. This package is stored in /usr/lib/fuzuli/nfl by default. Nfl packages (Nafile) have a similar file extension with the name Fuzuli. It means "useless" in English.

In Fuzuli, a package can be included using the require function:


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


Fuzuli has fopen, fwrite, fread and fclose functions for opening, writing, reading and closing of files,respectively. The code shown below shows how to open file for writing.

(let f (fopen "/tmp/example.txt" "w"))
(let liste (list 1 2 3 4 5 6 7 8 9 10 11 12 13 14))
(fwrite f liste)
(fclose f)


In the example above, we are opening the file example.txt for writing and writing elements of a list in it. This list contains integer numbers from 1 to 14. fwrite takes the reference of file and object to be written as parameters. A single element can be written in same manner. Finaly we are closing the file using 'fclose'. The example shown below shows how to read from values from the same file:

(let dd (fopen "/tmp/example.txt"  "r"))
(let a 0)
(let mysum 0)
(for (let i 0) (< i 5) (inc i)
                (let mysum (+ mysum (fread dd a)))
)


In the example above, dd is a reference to the example.txt. Note that, fopen shares the same file mode types with C++. So "r" means, the file will be opened in "read" mode. Variables "a" and "mysum" are set to zero before the loop. In loop, we are reading the next object using "fread" from the file reference "dd". mysum holds the sum of first 5 integers. The result is 15. Question: How fread knows the data type? The answer is easy. "a" is set using (let a 0) so a is an integer. If "a" is defined using (let a 0.1) then "a" is a double and fread will read a double from the file. In previous example, 5 objects were read from the file. Sometimes, it is impossible to know the number of records of objects that contained by the file. feof function can be used in a loop as in Fuzuli's parents.

(def a INTEGER)
(let dd (fopen "/tmp/kek.txt"  "r"))
(while (= (feof dd) 0)
        (block
                (print (fread dd a) " ")
        )
)
(fclose dd)


In the example above, the value of "a" is not set but it is defined as integer. We are reading from the file in a while loop and the stop condition is reaching the end of file. As we mentioned above, fread reads integers because of the type of variable "a". Fuzuli has several input and output functions beyond the file operations. The function fflush is used for writing bytes stored in the buffer.

(let f (fopen "/tmp/example.txt" "w"))
(let liste (list 1 2 3 4 5 6 7 8 9 10 11 12 13 14))
(fwrite f liste)
(fflush f)
(fclose f)


In the example above, fflush sends content of the file buffer to the opened file after each fwrite operation. getpdw function is to get the working directory:

(let mydir (getpwd))
(print mydir "\n")


With chdir, current path can be changed:

(chdir "/tmp")


Function dir returns a list of directories and files of a given directory:

(let mydir (dir "."))
(foreach direntry in mydir
        (block
                (print direntry "\n")
        )
)


In the example above, dir takes a parameter of "." so content of the current directory is shown. Function unlink and rename deletes and renames files, respectively:

(let mydir (dir "."))
(unlink "/tmp/example.txt")
(rename "1.txt" "2.txt")


In the example above, example.txt was deleted and name of 1.txt is set to 2.txt.

Fuzuli currently has those io functions in io.nfl:
  • fopen
  • fclose
  • feof
  • fwrite
  • fread
  • fflush
  • chdir
  • getpwd
  • dir
  • unlink
  • rename
  • tmpfile
  • tmpnam
  • datetime
  • asctime
  • sleep
  • getenv
  • rnd
  • print_r
  • popen
  • pclose

There are several input and output functions in Fuzuli. Please have a look at the Fuzuli Documentation in Fuzuli Source Code page for further information. We will explain the language and its libraries with more examples in next posts.

Wednesday, May 23, 2012

Fuzuli: A new general purpose interpreter and language

We are happy to announce that we have just released 0.1 revision of our general purpose interpreter Fuzuli.

Although Fuzuli has a syntax similar to Lisp, it is not intended to be a Lisp clone. We just wanted to have an interpreter that has lots of properties from both Algol and Lisp languages.

Fuzûlî is a 16th century poet, writer and thinker that lived in Ottoman Empire. Since his real name was Muhammad bin Suleyman, he used the name Fuzuli as his pen name. The name Fuzuli is very interesting because of its meaning. It means impertinent, improper, unnecessary in English. However it is an Arabic word with more than one meanings. With its primary meaning, Fuzuli has its roots from the word "science" and the word "arts". Please read more about the name and the poet Fuzuli in Wikipedia.

 It is not a coincidence, we choose this name for our interpreter because we had no motivation for writing it. We have just written it for fun! There are lots of languages that we use such as C, C++, Java, Php and Perl and  they satisfy what we need at all. Writing such a language was just a fuzuli work! Note that we are not computer science guys, so our code may not be a real king!

Fuzuli has been written in C++ and Fuzuli. It currently supports dynamic library loading, Algol type loops and control statements with a Lisp syntax, a primitive garbage collector, scopes for global and local variables, MySql databases and socket connections. It has an IO library that completely inherited from C++. It has libraries about GD2 and Tcl/Tk in an elementary manner. 

 The project page is hosted in Fuzuli Google Code page and the source code is ready for downloading and compiling. Our friends are preparing installation packages for several Linux Distributions such as Ubuntu and Slax. We are also working to build up a comprehensive documentation. Your help about coding, documentation, making packages for the other distributions, Windows and Mac binaries or anything else is also welcome! We also need your ideas and suggestions on Fuzuli for further revisions.

A fibonacci function written in Fuzuli is shown below:

(function fibonacci (params x)
     (block
        (if (<= x 2)
          (return 1)
          (return (+ (fibonacci (- x 1)) (fibonacci (- x 2))))
        )
     )
 ) 
 

This function is called using an expression similar to this:

(let result (fibonacci 5))

A list that contains integers from 1 to 10 can be written as:


(let alist (: 1 10))

and R users would be happy when they see the operator ':' in Fuzuli. A for loop is something like

(for (let i 0) (< i 10) (inc i)
   (block
      (print "i is " i "\n")
   )
)

in fuzuli. The variable 'i' is local and invisible to upper scopes, such as global scope. We define variables using a notation like this:

(def i INTEGER)
(def d FLOAT)
(def s STRING)

and variables are visible in the scope which they were created and scopes under that scope. Block, for, while and foreach expressions define blocks. For example 

(block
   (def i INTEGER)
   (let i 10)
)
(print i)

writes NULL because i is defined and set in a local block. However 

(def i INTEGER)
(block
  (let i 10)
)
(print i)

prints a "10" because the variable 'i' is defined at the top of the block.
We have implemented some functionality of Fuzuli in seperated dynamic libraries. The fuzuli package math.nfl has a content similar to
(let mathlib (dynload "FuzuliCore"))



(let PI (C mathlib "pi") 0)


(function sin (params x)
    (return (C mathlib "sind" x))
)

(function cos (params x)
    (return (C mathlib "cosd" x) )
)

(function tan (params x)
    (return (C mathlib "tand" x) )
)

This package loads the dynamic library FuzuliCore (it is libFuzuliCore.so in Linux) and defines some math functions. Actually, they do nothing but acting like wrappers. The fuzuli function 'C' is used to call C functions from fuzuli. In example below, C functions pi, sin, cos and tan are wrapped. The sin and the cos functions are defined as
Token *sind(Token *params, Environment *env){
    Token *resultToken = new Token(0.0, FLOAT);
    resultToken->setFloatValue(sin(params->tokens[0]->getFloatValue()));
    return(resultToken);
}

Token *cosd(Token *params, Environment *env){
    Token *resultToken = new Token(0.0, FLOAT);
    resultToken->setFloatValue(cos(params->tokens[0]->getFloatValue()));
    return(resultToken);
}


Note that this code is not integrated with our primitive garbage collector and the code should be

Token *sind(Token *params, Environment *env){
    Token *resultToken = env->newToken(0.0, FLOAT);
    resultToken->setFloatValue(sin(params->tokens[0]->getFloatValue()));
    return(resultToken);
}


Fuzuli can also used as a CGI language. It supports HTML tags in a manner similar to Php. Here, there is an interesting example:



The example shown below creates an HTML table with content of days of a week! The interesting point is that it starts with an html tag and it ends with html tag end. Setting this file as executable is what we need for running it as a CGI program.

We also plan to implement more languages that run in fuzuli.

Finally, Fuzuli is in its early stages. We need usage statistics, suggestions and ideas. We are also preparing the documentation. Follow us at stdioe!

Wednesday, May 2, 2012

Text & binary modes on ftp – CR LF ASCII codes


Why there are binary mode and text mode transfers?

What is the difference between binary and text mode transfers?

When FTP data transfer modes are important, When it doesn't matter?

Sometimes, I can see an unknown character like "^M" at and of a line, what is this character? Why is it there?

I have to talk about "how to recording data" when we are writing to a text file. Because, the questions above are directly related how to save text files on disk! As you know, there is a character table for text which is called ASCII code table as following,


When we press to a character on the keyboard while we are using a text editor, the text editor records them as equivalent value on the ascii table. For example, when we pressed the character "a", the editor saves it as hex "0x61". This situation is same for all Operating Systems.

BUT,

We see a text as lines of characters but normally all of the information is constructed by 1's and 0's. Those texts don't lie as lines in computer's memory. Text editors try to mark each line with special characters starting with a character. The problem is that when we press ENTER button on the keyboard, the text editors are using different marking information on different Operating Systems.

Let's continue our sample,
We want to write

"Hello\n"

"\n" part is for pressing ENTER button on the keyboard. This is a characteristic symbol in the C programming language. Content of that string is stored on Windows, Unix/Linux and Mac Operating Systems as follow;

54 65 73 74 0D 0A - On a Windows system
54 65 73 74 0A    - On a Unix/Linux system 
54 65 73 74 0D    - On a Mac system                 

0D and 0A parts are for illustrating CR and LF on ASCII table. CR means, "Carriage Return" and LF means "Line Feed". As you see below Microsoft Windows needs both to mark a new line however Unix / Linux operating system don't need both of them. CR is enough to show anew line. The Mac style is just the opposite of the Unix/Linux.

There are 255 characters in Ascii table. The extended part of Ascii table is other part as follows;



Just because for this reason, ftp protocol is supporting two different transfer mode.

Binary mode is transferring data from ftp client to ftp server bit by bit without any modification. If client and server have different type of operating systems, target system can not identify the line endings if the subject to send is text file.

Text mode is able to understand source and target system difference and fix the line ending codes as expected format by the requester.

So, If your system and  target ftp server are in different type and your data is text, you have to select text transfer mode on your ftp client to ensure files to be sent in correct form.

Saturday, April 14, 2012

Stdioe Starts Tweeting


We are happy to announce that we start to tweet at twitter.
Follow @stdioe for our updates, new articles and other news.
For the stdioe team, async:false.


twitter.com/stdioe



Wednesday, March 28, 2012

Using PHP-GTK to Serve Desktop Applications: Creating a Simple Interface

PHP-GTK is a library for PHP that provides an object-oriented interface to GTK+ classes and functions. Actually this is a little bit hard, so that is slow to develop itself. PHP-GTK uses object-oriented programming on it.

What is PHP-GTK?

GTK is a library to develop PHP and created by Andrei Ziminevski, you want to see him? There are some varieties about that, Scintilla, GtkHTML, etc.
According to some of us, Java, C++ or C# is better to use than PHP-GTK. But If the coder who knows how to code on PHP use it, PHP-GTK should be very simple to code. That's why is OOP kind of PHP 5.

Installing PHP-GTK for Windows
Had you set any plugin up before, you shall say that, installing PHP-GTK plugin is so hard, but actually is not'cuz you have to know something about that. First go this site: gtk.php.net or here and download gtk library. After that open the .rar or .zip file you've just downloaded.

Download gtk library: gtk.php.net
When you open this archive, just copy all folders to C:/
After this, open the winnt folder and copy the php.ini file, paste to php4 folder. And finish! You have finally finished the installing right now!
This one is for windows installation. If you want to install this package other system (Linux, MacOS something else), you can visit this official page.


The First GTK Project!
As we know, when the first project created, just done "hello world!". What we're gonna do is like that :) For this we need to php code and GTK library. that's it!
helloworld! MyFirstProject.php file

function clearThis() {
  Gtk::main_quit();
}
$window = new GtkWindow(); 
$window->connect('destroy','clearThis');

$window->set_border_width('50'); //Alert's width set as 50px.

$label = new GtkLabel("Hello World"); //Written Text sets here.
$window->add($label);

$window->show_all();
Gtk::main();
It is time to work the project. First open your windows command screen and follow this directory: c:\php4\php c:\php4\test\MyFirstProject
Output
Well, we have installed PHP-GTK library on C:/ and created the first project about it. As result, we can say, PHP language is not just for the web, can use it as desktop.


See you guys next article!

How to Connect SQLite Database in Android & A Simple App: "Accessing Data With Android Cursors"

Hi Everyone! I'd showed you how to do an application on Android in the last article. This one is going to be about connection SQLite database and access data with cursors.

If you want to use your data or something else, should connect a database. Using SQLite on Android is so simple. There are so much SQLite Editor but I will use Firefox SQLite Manager in this article. For that, first open your Firefox Browser, then download SQLite Manager and as result go this directory: Tools/SQLite Manager. After that, you can range database. 

And now, it's time to ready our files we use to. Just follow this directories:


Documents:
1- src/DatabaseActivity.java
2- src/Database.java
3- layout/data.xml

We need "database.java" file, that's why is gotta a table on database. If you want to add something, I must have a database. Now, code Database.java file.
package database.connection;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;


public class Database extends SQLiteOpenHelper {
 private static final String MYDATABASE = "names";
 private static final int VERSION = 1;

 public Database(Context connection) {
  super(connection, MYDATABASE, null, VERSION);
 }

 @Override
 public void onCreate(SQLiteDatabase db) {
  db.execSQL("CREATE TABLE mynames(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT);");
 }

 @Override
 public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
  db.execSQL("DROP TABLE IF EXIST mynames");
  onCreate(db);
 }
}

So, we've just created a database, as called MYDATABASE. Table's name is "names". There are two fields on it: "id and name". As you know that is all about SQL. If you know SQL, you can get it easily. id field is an integer piece of table. The other one is a text field.

We'got a database and a table of this. The form we can add data is what we need exactly. For that, gotta compose a Android XML File. This file will have a textfield widget and a button widget, that's it! Let's do data.xml file!


    
        
    

    

If you want, just look what we got up right now. We created a database, a table of this database and form widgets. I can add a data after make this platform up:) Let's do our platform: DatabaseActivity.java file
package database.connection;
//Those are included by the system 
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
 
public class DataBaseActivity extends Activity {
    private DB names;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.data); //including layout/data.xml file
        names = new DB(this);
        final EditText name=(EditText) findViewById(R.id.editText1);
 
        Button senddata=(Button) findViewById(R.id.senddata);
 
        senddata.setOnClickListener(new View.OnClickListener() {
 
            public void onClick(View v) {
                    try{
                     AddDATA(name.getText().toString());
                     Cursor cursor = ShowDATA();
                     ShowDATA(cursor);
                     }
                     finally{
                     names.close();
                    }
            }
        });
 
    }
    
    private void AddDATA(String ResultName){

    SQLiteDatabase db = names.getWritableDatabase();
    ContentValues datas = new ContentValues();
    datas.put("name", ResultName);
    db.insertOrThrow("ournames", null, datas);
    }

    private String[] SELECT = {"id", "name"};

    private Cursor ShowDATA(){
    SQLiteDatabase db = names.getReadableDatabase();
    Cursor cursor = db.query("ournames", SELECT, null, null, null, null, null);

    startManagingCursor(cursor);
    return cursor;
    }

    private void ShowDATA(Cursor cursor){
        StringBuilder builder = new StringBuilder("RESULTS!:\n");

        while(cursor.moveToNext()){

        String whatthenameis = cursor.getString((cursor.getColumnIndex("name")));
        builder.append(whatthenameis).append("\n");
        }

        TextView text = (TextView)findViewById(R.id.textView1);
        text.setText(builder);
    }
}
Generally, coder need to use a database, while saving data. We use SQLite Database on Android'cuz it's simple. Here, SQL is as you know before. "SELECT" command using also. By the way, if you want to check your db file out, just go this directory on Eclipse: file explorer/data/[your project name]/database
Write Something
That's it! We can add and save our datas, through SQLite Database on Android.
When you write something and click button, data will been saved and can show it on the screen. We'll you guys next article!

Saturday, March 10, 2012

Developing a Basic Application on Android: "Welcome Page"

Hi Everyone! Today, I'll show you an Android application which is about welcome pages. As known, before when opened an app, game, web site, DVD movie, etc, a welcome page has shown us by masters of'em. That's why is showing what the brand is. For example, Angry Birds, EA Games, Microsoft Games.

This article is going to be a basic application like "Hello World!". But Before we'll be on welcome page and see the welcome message on it. Let's see how to do it!

Necessary equipment (Install all of them)
  1. Eclipse Editor
  2. SDK (Software Development Kid)
  3. Android: WindowsLinuxMac
First, open the Eclipse editor, then follow this directory: File/New/Project/Android/Android Project
My Project Name : WelcomePage
My Android Version : V2.2
My Package Name : welcome.page
You can fix this properties as you wish.

I think, you know how to do an "hello world" app on Android, so I won't explain this. The important thing of the app for me is relationship of Activities and Threads. For those, we're going to do this pages:
src/WelcomePageActivity.class //This is a default file
src/WelcomePage.class
res/layout/main.xml //This is also a default file
res/layout/page2.xml
AndroidManifest.xml //This is configuration file
Create a class file: 
  1. directory: src/(Right Click)New/Class
  2. call: WelcomePage
  3. Click the "Finish" Button
Code for WelcomePage.java:
package welcome.page;

import android.app.Activity;
import android.os.Bundle;

public class WelcomePage extends Activity { //Created WelcomePage Activity
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main); //The content to display from main.xml
 }
}

The "R" is a library which used for xml files. Every xml file can used on it. We'd just used main.xml file for we need to go home page of our Android app after showing welcome page.

Create a xml file:
  1. directory: res/layout/(Right Click)Other/File/Android/Android Xml File
  2. call: page2
  3. Click the "Finish" Button
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is a welcome page!" />

</LinearLayout>

When we look at this page up, should see like that:
page2.xml file view
Create WelcomePageActivity.java file
package welcome.page;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

public class WelcomePageActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page2); //The content to display from page2.xml file
        
        Thread WelcomeScreen = new Thread() { //Must create a thread, because opening another page is a different event, as sync
         public void run() {
          try { //This is try-catch
           sleep(5000); //Waiting five seconds
           startActivity(new Intent(getApplicationContext(),WelcomePage.class)); 
           //After waiting, shown the content from WelcomePage.java file
          } catch (InterruptedException e) {
           e.printStackTrace();
          }
          finally {
           finish(); //We finish this thread.
          }
         }
        };
        WelcomeScreen.start(); //Starting the thread created.
    }
}

Maybe, you may not get the line, 
"startActivity(new Intent(getApplicationContext(),WelcomePage.class));". 
Just remember that we used main.xml content to get on WelcomePage.java page.

And the last one we have to do, update AndroidManifest.xml file! Remember that we create a new Activity, so must define this Activity. For that reason, just add this code to AndroidManifest.xml file:
And yes, finished! Let's work this on our Emulator! For this, call: 


WelcomePage Project(Right Click)/Run as/Android Project

Welcome page view
After 5 seconds this page, we will see main.xml file:

main.xml file on my application
We'll see you guys next article!

Wednesday, February 1, 2012

Making bootable Slax Usb in Ubuntu

It is a problem to make a bootable USB flash disk in Ubuntu as I see in the Slax Forums. Slax can be installed in a Fat formatted USB disk or a CD-Rom. However, for the need for compactness, people generally chooses the first option in order to use an "install once and use anywhere" operating system.

Unfortunately, if you are using an Ubuntu OS and you want to make a Slax Bootable USB, problem arises. Since the USB must be formatted as FAT, you can not change the owners and permissions of files and directories. So that, we can not set a file executable. And simply writing a

usbdisk/boot> bash bootinst.sh

command cannot handle the problem. But the solution is easy.

First, download the Slax tar file for USB disks. Untar it. You have two folders. One of them is 'slax' and the other is 'boot'. Copy the 'boot' folder in your harddisk. Write

harddisk/some folder/boot> chmod -R a+x *

So, the copied boot folder is now fully executable. Suppose that  the 'some folder' is '/usr/local/bin'. Goto usb disk. Change directory to 'boot'. Edit the bootinst.sh

usbdisk> vim bootinst.sh


And change the content of the bootinst.sh file as following:



#!/bin/bash

set -e
TARGET=""
MBR=""

# Find out which partition or disk are we using
MYMNT=$(cd -P $(dirname $0) ; pwd)
while [ "$MYMNT" != "" -a "$MYMNT" != "." -a "$MYMNT" != "/" ]; do
   TARGET=$(egrep "[^[:space:]]+[[:space:]]+$MYMNT[[:space:]]+" /proc/mounts | cut -d " " -f 1)
   if [ "$TARGET" != "" ]; then break; fi
   MYMNT=$(dirname "$MYMNT")
done

if [ "$TARGET" = "" ]; then
   echo "Can't find device to install to."
   echo "Make sure you run this script from a mounted device."
   exit 1
fi

if [ "$(cat /proc/mounts | grep "^$TARGET" | grep noexec)" ]; then
   echo "The disk $TARGET is mounted with noexec parameter, trying to remount..."
   mount -o remount,exec "$TARGET"
fi

MBR=$(echo "$TARGET" | sed -r "s/[0-9]+\$//g")
NUM=${TARGET:${#MBR}}
cd "$MYMNT"

clear
echo "-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-"
echo "                        Welcome to Slax boot installer                         "
echo "-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-"
echo
echo "This installer will setup disk $TARGET to boot only Slax."
if [ "$MBR" != "$TARGET" ]; then
   echo
   echo "Warning! Master boot record (MBR) of $MBR will be overwritten."
   echo "If you use $MBR to boot any existing operating system, it will not work"
   echo "anymore. Only Slax will boot from this device. Be careful!"
fi
echo
echo "Press any key to continue, or Ctrl+C to abort..."
read junk
clear

echo "Flushing filesystem buffers, this may take a while..."
sync

# setup MBR if the device is not in superfloppy format
if [ "$MBR" != "$TARGET" ]; then
   echo "Setting up MBR on $MBR..."
   /usr/local/bin/syslinux/lilo -S /dev/null -M $MBR ext # this must be here to support -A for extended partitions
   echo "Activating partition $TARGET..."
   /usr/local/bin/syslinux/lilo -S /dev/null -A $MBR $NUM
   echo "Updating MBR on $MBR..." # this must be here because LILO mbr is bad. mbr.bin is from syslinux
   cat /usr/local/bin/syslinux/mbr.bin > $MBR
fi

echo "Setting up boot record for $TARGET..."
  /usr/local/bin/syslinux/syslinux -d boot/syslinux $TARGET

echo "Disk $TARGET should be bootable now. Installation finished."

echo
echo "Read the information above and then press any key to exit..."
read junk 
 
 
Save the file. Exit to shell. Type

usbdisk/boot> sudo bash bootinst.sh


By now, bootinst.sh runs the needed commands from /usr/local/bin not from /usbdisk/boot.


Happy installs...

Tuesday, January 31, 2012

A tiny C library for client sockets

Sockets are everything in programming, especially, after the wide use of internet. Sockets are used for connecting two devices in a network using several low level protocols. At user level, those protocols are not transparent to user, that is, opening a connection and sending some string or binary data along a network is the whole thing for a general programmer.

Socket programming is not a difficult one in much of high level languages. I have used sockets in Java several times and the stuff were running like a charm. Unfortunately, same easiness is not current for C. However, it is the faster way of doing this work.

Last day, I needed to code a client socket for retrieving some data over the network. My Ubuntu was ready for the task with its installed C libraries. Since Linux sockets are a little bit detailed so there were too many terms (htons, inet_ntoa) which requires some low level knowledge of Linux sockets. For example, a C# programmer does not need to know how Windows converts an IP number to binary data and via versa. But Linux sockets are harder. But once you learn it, it is more fun.

Finally, I wrote a small library for a client socket task. The example of this code is shown below:

(Test.c)
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include "ClientSocket.h"
  5.  
  6.  
  7. int main(int argc, char** argv) {
  8. /* We will store some text in this buffer */
  9. int bufsize=1024;
  10. char buffer[bufsize];
  11. char *hostname = "blogspot.com";
  12. int port = 80;
  13. /* Getting ip address of google.com into buffer */
  14. getIPAddress("google.com", buffer);
  15. printf("Connecting to (%s) %s\n", hostname, buffer);
  16. /* Creating socket */
  17. struct ClientSocket *socket = socket_create(buffer, port);
  18. /* Connecting */
  19. socket_connect(socket);
  20. /* Sending a http request */
  21. strcpy(buffer,"GET /\n\n");
  22. socket_send(socket, buffer, strlen(buffer));
  23. /* Receiving the first #bufsize elements */
  24. socket_receive(socket, buffer, bufsize);
  25. printf("%s",buffer);
  26. /* Do not read any more. Closing */
  27. socket_close(socket);
  28. return (EXIT_SUCCESS);
  29. }
  30.  
 



The header file of out tiny library is here:(ClientSocket.h)
  1. /*
  2. * File: ClientSocket.h
  3. * Author: Practical Code Solutions
  4. *
  5. * Created on January 31, 2012, 9:56 AM
  6. */
  7.  
  8. #ifndef CLIENTSOCKET_H
  9. #define CLIENTSOCKET_H
  10.  
  11. #ifdef __cplusplus
  12. extern "C" {
  13. #endif
  14.  
  15. struct ClientSocket {
  16. int fd;
  17. char *ip;
  18. int port;
  19. int (*getIp)(const char *, char *);
  20. };
  21.  
  22. int getIPAddress(const char *host, char *ip);
  23.  
  24. struct ClientSocket *socket_create(char *ip, int port);
  25.  
  26. int socket_connect(struct ClientSocket *sock);
  27.  
  28. int socket_send(struct ClientSocket *sock, char *data, int len);
  29.  
  30. int socket_receive(struct ClientSocket *sock, char *data, int len);
  31.  
  32. int socket_close(struct ClientSocket *sock);
  33.  
  34.  
  35.  
  36. #ifdef __cplusplus
  37. }
  38. #endif
  39.  
  40. #endif /* CLIENTSOCKET_H */
  41.  
The C source file of our tiny library is here: (ClientSocket.c)
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <arpa/inet.h>
  5. #include <sys/socket.h>
  6. #include <netdb.h>
  7.  
  8. #include "ClientSocket.h"
  9.  
  10. int getIPAddress(const char *host, char *ip){
  11. struct hostent *hh = gethostbyname(host);
  12. struct in_addr *add = hh->h_addr_list[0];
  13. strcpy(ip, inet_ntoa(add[0]));
  14. }
  15.  
  16. struct ClientSocket *socket_create(char *ip, int port){
  17. struct ClientSocket *socket = malloc(sizeof(struct ClientSocket));
  18. socket->ip = ip;
  19. socket->port = port;
  20. socket->getIp = getIPAddress;
  21. return(socket);
  22. }
  23.  
  24. int socket_connect(struct ClientSocket *sock){
  25. struct sockaddr_in addr;
  26. int result;
  27. sock->fd = socket(AF_INET, SOCK_STREAM, 0);
  28. memset((char *)&addr, 0, sizeof(addr));
  29. addr.sin_port = htons(sock->port);
  30. addr.sin_family = AF_INET;
  31. addr.sin_addr.s_addr = inet_addr(sock->ip);
  32. result = connect(sock->fd, (struct sockaddr *)&addr, sizeof(addr));
  33. return(result);
  34. }
  35.  
  36. int socket_send(struct ClientSocket *sock, char *data, int len){
  37. return send(sock->fd, data, len, 0);
  38. }
  39.  
  40. int socket_receive(struct ClientSocket *sock, char *data, int len){
  41. data[len-1] = '\0';
  42. return recv(sock->fd, (void *)data, len -1 , 0);
  43. }
  44.  
  45. int socket_close(struct ClientSocket *sock){
  46. return close (sock->;fd);
  47. }