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.

Monday, November 28, 2011

making a ThinClient OS with pxeboot support


When I needed a thin client for the company which I am working for, I firstly researched some existing products on the market. (wise, chipPc etc.) Actually, there were some good things but I needed a more customizable one. When the subject is about customization, I have got an unique address for solution: that's
linux. I wanted to create a simple, easy to setup and strong solution. I checked following criterias:
  1. I had to use a complete distrubution to start to work. Because, all distrubutions are ready for use. I didn't need to handle more to start.
  2. I had to create image file/files as OS. It should be open from image / images files every times. Therefore, It can keep ifself as strong.
  3. If I could supply the Boot On Lan feature on my pxeboot server, the clients would never get damaged in the future. Because all clients would run on only their RAM device. Altough they had been shutdown un-properly, they could stil read the original image file from the pxeboot server. I only needed keep the image file safe which is located on the pxeboot server.
I researched a few distros and than I selected the SLAX for my project. It's using squash FS (lzm files). It seemed the best choice for my requirements about the image.. SLAX distro is normally used on the usb devices. It's a kind of mobile version of Linux. You can use it in several hardwares.

However; I had to change something on standard SLAX. The history of my project begins.

In order to install Slax, download the USB image from site "http://www.slax.org/get_slax.php". After extracting it, it will generate two different directories: slax and boot. Firstly we need dir2lzm and lzm2dir scripts/commands to extract lzm files and to re-build the lzm file again. These are located in the directory /slax/tools/.


Slax has got a very nice structure. Making manipulations are very easy and controllable. For example, you can create a module file to create some changes from original slax and you can apply this changes by a single copy-paste operation. There is a director, with name modules, exists for this purpose. After starting to make changes in 001-core.lzm file located in base directory, I realized that this was not a good way.

Note: Your linux (also windows OS) has got a variable about default PATH to find predefined commands on your operating system. But your tools directory (located in Slax directory) is not included in the PATH variable. So if you try to execute lzm2dir command in somewhere, you will not be able to execute it. You can execute it with a full path or you can execute it with "./lzm2dir" command when you are located in tools directory or you can add your tools directory it to the PATH. Most useful way is adding the tools directory into the your PATH variable. Suppose that your Slax directory is located in the /home/User. We can get and set the PATH environment variable as shown below:

[user@hostn stdioe]#  /home/User/slax
[user@hostn stdioe]# /home/User/slax/tools <- related commands located in here
[user@hostn stdioe]# echo $PATH <- to check existing value of your PATH variable
/usr/lib/mpi/gcc/openmpi/bin:/home/User/bin:/usr/local/bin:/usr/bin:/bin:/usr/bin/X11:/usr/X11R6/bin:/usr/games:/opt/kde3/bin:/usr/lib/mit/bin:/usr/lib/mit/sbin
[user@hostn stdioe]# PATH=$PATH:/home/User/slax/tools <- to add slax-tools directory to in your PATH variable

Good, We can use that commands from everywhere by now. Let's extract the 001-core.lzm file to do some manipulations.

Note: Actually, that commands are just several simple shell scripts. The real commands are squash FS commands. If squash FS is not installed in your operaing system, you can not use the tools directory scripts. You have to have squashfs installed on your system. The squashfs is a read-only file system with efficient compression property. It's essential and base thing so, almost all distrubutions has got it in their package manager. You can install it using your package manager.

Let's extract the file 001-base.lzm and start to manipulation step; I created a stdioe directory and copied the file 001-core.lzm to the the directory stdioe. I created a directory called core_Dir to extract contents of the lzm to the directory core_Dir.

[user@hostn stdioe]# pwd
/root/stdioe
[user@hostn stdioe]# ls
001-core.lzm
[user@hostn stdioe]# mkdir core_Dir
[user@hostn stdioe]# lzm2dir 001-core.lzm core_Dir/
TIOCGWINZ ioctl failed, defaulting to 80 columns
[===========================================================-] 12069/12069 100%[root@ismldgn stdioe]#
[user@hostn stdioe]# ls
001-core.lzm core_Dir
[user@hostn stdioe]# cd core_Dir/
[user@hostn core_Dir]# ls
bin dev home media opt root srv tmp var
boot etc lib mnt proc sbin sys usr
[user@hostn core_Dir]#

core_Dir directory is a container for our thin client OS file structure. First of all, we have to focus on the file /etc/rc.d/rd.M. The file manager starts up the process.

We will create an image file which will then be used by our thinclients. So if we don't solve the problem of hostnames, all our thinclients will have got the exactly same hostnames. The main problem is, all of them connect to the same terminal server. The terminal server can not handle the connections properly. If you look from terminal server side, you can see a lot of clients are connected but all names are the same!

Normally rc.M assigns a hostname from contents of the file /etc/hosts. My offer is, we can create a new and different hostname for each client while booting progress. The mac address information already provides an unique information for this. We can use the mac to assign them different names! We can edit our commands after the line in which it is written "# Initialize the networking hardware.".



ls -aA1b /etc/dhcpc | egrep ".info\$" | while read INFOFILE; do
# the next line won't affect rc.M variables, because it's in >while read< loop
. /etc/dhcpc/$INFOFILE
echo "TPL`/sbin/ifconfig | /bin/grep "HWaddr" | /bin/gawk -F' ' '{print $5}' | gawk -F: '{print $1$2$3$4$5$6}'`."$DOMAIN >/etc/HOSTNAME
sed -i -r "s:127.0.0.1\tslax.*:127.0.0.1\tslax.$DOMAIN slax:" /etc/hosts
break
done

Well. Now, each client has got a different hostname. All hostnames start with a TPL prefix and continue the mac info without ":" and ".$DOMAIN" variable, respectively. If you don't need FQDN name, do not use the ".$DOMAIN" part.

This OS will be used as a thin client os. So the main goal is to "connect to the terminal server". We don't need advance graphical user interface. We need simple a simple solution. I selected fluxbox for this purpose. When the OS starts, the fluxbox should be opened automaticly. For this purpose, we have to add the content shown below with a ".xprofile" name in the "/root" directory. This configuration is to start the fluxbox GUI.

session=/usr/bin/startfluxbox
/usr/bin/setxkbmap tr
#/usr/bin/rdesktop terminalServerAddr -f -r printer:oki="Epson LX-80" -k language

The -k option is for defining the language. Please replace the proper language code for your language. The line marked with a '#' supplies a connection to the terminal server automaticly but I marked it to make it disabled, because user may want to do a different thing. So we have to create a menu file for fluxbox GUI. Let's create a lzm file again from the edited base package and create a new module file for other purposes.

[user@hostn stdioe]# 
[user@hostn stdioe]#
[user@hostn stdioe]# ls stdioeBase/
bin boot dev etc home lib media mnt opt proc root sbin srv sys tmp unsped usr var
[user@hostn stdioe]# dir2lzm stdioeBase/ 001-base-edited.lzm
[=============- ] 2337/10544 22%

Right now, our base lzm file is ready. But normally we have to create a module file for our changes. We don't have to handle the original base file. because when we a new release is published, we will need to handle it again. But if we create a module file, the copy paste operation will probably be enough for this. Also the module mechanism is very useful feature. Let's create a module file for other requirements,

[user@hostn stdioe]# mkdir nameOfModule
[user@hostn stdioe]# mkdir nameOfModule/root
[user@hostn stdioe]# mkdir nameOfModule/sbin
[user@hostn stdioe]# cd nameOfModule/root
[user@hostn stdioe]# mkdir .fluxbox
[user@hostn stdioe]# cd .fluxbox
[user@hostn stdioe]# vim menu

Content of the menu file is shown below:

[begin] ('The Project Name' - MENU)
[encoding] {UTF-8}
[submenu] (Tools)
[exec] (Command Window) {xterm}
[exec] (Internet Browser) {kfmclient openProfile webbrowsing}
[exec] (Text Editor) {kwrite}
[restart] (KDE GUI) {startkde}
[end]
[submenu] (Remote Desktop : termSrv.dom)
[exec] (800x600) {termsrvDOMr1}
[exec] (1024x768) {termsrvDOMr2}
[exec] (Tam Ekran) {termsrvDOMrf}
[end]
[exec] (Shutdown Computer) {pcShutdown}
[endencoding]
[end]

Of course, some used commands are not default ones. These are user defined. We have to write them and set execution permissions and locate them into a proper directory as value of $PATH variable. That files are listed below.

pcshutdown:

#!/bin/bash
init 0

Note: Our thin client os is already running on the RAM. So we can shutdown up-properly. "init 0" is the most rough way.

termsrvDOMr1:

#!/bin/bash
/usr/bin/rdesktop termsrv.DOM -g 800x600 -k tr -r printer:UGLpoki="Epson LX-80" -d DOMAINNAME -u ""

termsrvDOMr2:

#!/bin/bash
/usr/bin/rdesktop termsrv.DOM -g 1024x768 -k tr -r printer:UGLpoki="Epson LX-80" -d DOMAINNAME -u ""

termsrvDOMrf:

#!/bin/bash
/usr/bin/rdesktop termsrv.DOM -f -k tr -r printer:UGLpoki="Epson LX-80" -d DOMAINNAME -u ""

Finally set to execute permission and copy it to /sbin directory. After all, create lzm file of the module.

[user@hostn stdioe]# chmod +x pcshutdown termsrvDOMr1 termsrvDOMr2 termsrvDOMrf
[user@hostn stdioe]# cp pcshutdown termsrvDOMr1 termsrvDOMr2 termsrvDOMrf nameOfModule/sbin/
[user@hostn stdioe]# dir2lzm nameOfModule nameOfModule.lzm
[===================================================================|] 6/6 100% [user@hostn stdioe]#
[user@hostn stdioe]#

Right now, if we copy that lzm module file to modules directory, this module will be enabled when booting the OS automaticly. But we still don't create a module for printer driver and configuration. That file content is a little bit long so explaining how to create a printing module is not a good idea in this.. But you can use a usb version of Slax and open it with "Slax Graphics mode" option and install printer driver and configure it then shutdown properly. Then, if you check directory changes, you can find all changes about the printer installations and configurations. The problem is, existing files are not only about the print functionalty. You have to select printer related ones. I can create a download link in this page, but usually it is not a good idea to create a download link about any file. If some body want to download that file, I will send it.

Good. Our thinClient OS is ready. We prepare it from the usb version of Slax. And now, we will prepare a tftp server and http server to get the pxeboot server ready. TFTP server installation and web server intallation are not related to this article, so I don't explain it. But I have to say again, your http server should be a permitted directory and configured as indexing compatible with httpfs property. Because, when the boot process starts, our pxeboot server will send the boot parameters via tftp server and than starts to use the https service for loading big files. Because tftp is a UDP based service and http is a TCP based service. Nobody wants to use UDP based service to load big files. So UDP does not check the data whereas TCP uses a checking mechanism while data is transfering.

The boot directory should be located in the directory "tftproot" and Slax directory should be located in the http publishing root directory. (/var/www/html or /srv/www or something like that).

The last step is to configure the DHCP server for pxe booting. My project environment has got a Microsoft Windows 2003 Server for DHCP server. When you right click to scope option and select the configure option in this DHCP server, you can see a window. This window has got "066 Boot Server host Name" and "067 Boot File Name" options lines. You have to add the ip address of your pxeboot server to "066 Boot Server host Name" option and write "/boot/pxelinux.0" for "067 Boot File Name" option. Right now, if you set "boot on lan" option in a client computer bios, as a client computer starts, it will search a DHCP server, and it will learn pxe boot server address, file name info, the boot parameters from the tftp server and OS files from pxeboot server via httpfs service, respectively.


Content of the file /tftproot/boot/pxelinux.cfg/default is shown below:

PROMPT 0

LABEL linux
MENU LABEL Run linux over PXE
KERNEL /vmlinuz
IPAPPEND 1
APPEND vga=769 initrd=/initrd.gz ramdisk_size=6666 root=/dev/ram0 password=qwe123 rw autoexec=xconf;telinit~4

LABEL memtest86
MENU LABEL Run Memtest utility
KERNEL /mt86p

This project is suitable to be developed more.. I created more than one configuration files. When the boot process starts, it will be able to read mac address and get the configuration as its mac info. So we can make more than one groups. Each single member of the group can read different module files and configurations. For example, you can create two different groups and than you can include some mac addresses of that groups. Every group have got a single configuration file. Therefore, every client will use their own setting. By the way, I think the most powerfull feature of this OS is, It will never crash!. Because it will use the same lzm file for booting process. If you can create a usable OS, you will always be able to use it. Itwill never need "disk defragmentation" or something like this...

String ambiguity in Java



Java has two kind of data types. The first one includes the primitive data types. They are int, long, double
float, short, byte, boolean and char. Defining a single variable with one of the data types given above is similar
to variable declaration in C or C++. As in C brother, Java simply allocates a proper memory area for the given
type and maps the variable name for it when we type

int i;

in a program. It is simple to understand and clear. The mechanism underlying instantiating a class to create a new object
is similar to C++. For example, we create an object by instantiating a CCObject class using

CCObject *obj = new CCObject();


in C++, whereas, it is

CCObject obj = new CCObject();


in Java. In C++ example, a memory area is allocated for the CCObject and it is mapped to pointer obj which is shown as *obj.
We call its method "meth" using a code similar to

obj->meth();

whereas, it is

obj.meth();

in java. They are both created using a dynamic loading mechanism, that is, they does not exist in compile time and they
are created in runtime. In this use of "->" operator, object instantiating mechanisms are similar. However there is an
other method of creating objects in C++ which is like

CCObject obj;
obj.meth();


and it is totally different from the examples above. In this example, the object obj is created at the compile time
and it is faster. The dot operator is also different from the same operator in Java. Understanding the dynamic class
instantiating and compile time creating is important.

Lets have a look at the String class in Java, which is defined in the package java.lang in the Java core library. We can
create two Strings using a code

String s1 = "This is string 1";
String s2 = "And this is the second one!";

and we can do

String cat = s1 + s2;

which requires a "operator overloading" operation in C++. In Java, there is no operator overloading, that is, you can
not define a behavior for a given operator on a given class. But String class do that!

String class is an exception and it has got different properties when compared to others. Java compiler behaves different
when it compiles the codes with a String object. The another ambiguity is using literals with class methods. Look that:

String s = "Hello, this is a curse Java string";

This use seems like the Java Strings are built-in data types rather than objects! Ofcourse, Java compiler changes this line to

String s = new String("Hello, this is a curse Java string");

but what about this? :

int l = "Hello, this is a curse Java string".length;

If a Java student looks this line, the Java String seems to be an object again! This is because of the weird design of Java Strings.
Java compiles them in a consistent way but being Java Strings a exception obstructs the clean pattern of Java language.

What is the solution?

Firstly, for my personel opinion, operator overloading would be a good property for Java language. So, it would be a more elegant solution
to drop this

Matrix A = new Matrix (data1);
Matrix B = new Matrix (data2);
Matrix C = A.transpose().product(A).inverse().product(A.transpose().product(B.transpose));

and replace with

Matrix A = new Matrix (data1);
Matrix B = new Matrix (data2);
Matrix C = (A.transpose() * A).inverse() * A.transpose() * B.transpose();

This provides the consistency in the use of summation operator with String classes.

Dropping the ambiguity in the cases that "a string content".length and String s = "This is a string" is hard because millions of
Java code uses this syntax. Deprecating this use and dropping it in next revision is a solution. It would be still as it is. But
remember the Basic language and remember how difficult to parse it was. Writing code in an easy way is not the whole art. A consistent
language is like an deterministic toolbox.

My radical idea is to use the C++ syntax in Java virtual machine. Something must be an object, something must be a pointer to an object. Operators
would be overloaded as "Java does it to its Strings!". So, how it would be nice if we compile this code into the JVM:

String *s = new String("Hello there, it would be a Java String!");
int length = s->length;
System::out::println(*s->chars);

and of course

String s = String("Hello there... it is also a Java String");
int length = s.length;
System::out::println(&s.chars);

:)

Moreoever, there would be some strangers around who want their C++ syntaxed Java code compiled into the JVM!

Tuesday, November 15, 2011

Web 2.0 Tech and a Jquery Auto Search Complete Application!

Hi! Today I want to talk about web 2.0 technology. As you know, web 2.0 is being used by many of us. Especially frameworks developed with javascript and ajax, used by everyone. Well, we can say that huge companies which are google, yahoo, facebook and twitter etc. use web 2.0 too.

I would like to make an application on Jquery and share with you guys. So, in 2006, Jquery's started to be developed as an open source project. When you see "The write less, do more", you should understand that is Jquery! There is a powerful library of javascript, that's why we can do good jobs with the less code on Jquery.

If you want to see more information, you can visit the official web site of jquery. You can also find documentation and examples on it. That is here!

You must call as include jquery library on your web site, for the successful operation of your jquery code. You can find the library on Jquery Web Site easily.

The point I wanted to show you here is an ajax application on jquery. However, I am thinkin' that I should show you couple simple examples, before starting to applicaton.

$('#divID').slideUp(1000); //Sliding the div up
$('#divID').slideDown(1000); //Sliding the div down
$('#divID').slideToggle(1000); //Sliding the div up and down
$('#divID').FadeToggle(1000); //Displaying or hiding the div
$('#divID').html(“Hello World!”); //Printing something as HTML tags

$(‘a’).click(function() {
 $("#divID").animate({left:'+=100px'}, 2000); //when you click the mouse, do something
});

As you have seen, when you code jquery, you can control the web site all the way.
The application I'll show you, is an AUTO SEARCH COMPLETE!


This is the text field we'll use when searching.


This is the div layer will open during our php script works.
// JavaScript Document
$(document).ready(function() {
 $('#TextBox').keyup(function() {
  document.getElementById("result").style.display="block";
  var variable=$('#TextBox').val();
  $.ajax({
      url:"data.php",
      data:"TextBox="+variable,
      cache:false,
      async:false,
      method:'post',
      success:function(kitchen) {
          var message="Loading..";
          $('#result').html(message).load();
      }
  });
 });       
});

As you have seen, when keyup() function works, the system is getting data from data.php page. data.php page is shown below

 include("database.php");
 $data=$_REQUEST["TextBox"];
 if(!$data==0) { 
  $MyData=mysql_query("select * from names where name like '%$data%'");
  if(mysql_num_rows($MyData)<"1") {
   echo "There is nothing about it!"; 
  } else {
   echo "Languages!
"; while($MyList=mysql_fetch_array($MyData)) { echo $MyList["name"]."\n"; } } } else { echo "Please, start to write something.."; }


Today, we made a jquery search auto complete application. If you visit and see this application, just click demo page!

See you guys next article!

Monday, November 14, 2011

A Nokia application for system room temperature controlling.

One of the our previous article ( http://stdioe.blogspot.com/2011/10/checking-system-room-temperature-with.html ) was explaining how to get temperature information from some devices. We showed that related scripts saves the temperature value to a MySQL table. In this article, we are explaining publishing only the current temperature value on a public web page. The Nokia application will read that value to generate alarms when the value exceeds a critical value. The Nokia application is written by jbytecode to follow up via cell phones. If system room temperature reaches a predefined critical value, your mobile cell phone will create an alarm sound. Therefore you will be informed where ever you are.

The mobile phone application is an open source project and is being hosted on Google Code web site. You can access .jar and .jad files and source code on http://code.google.com/p/atlantis-networking-utilities web page address.Note that we call that "Nokia Application" because we only tested it with a Nokia E-72. Of course it is generally a Midlet application which can run in any supported device.

You can start the application by simply clicking the icon,

You have to define a temperature reader url on that program. If you need, you can change the checking period of system room temperature and define a critical temperature value,

After editing the configuration you can start the application,


The application needs internet connectivity. When it starts, it will show a confirmation alert and wait your response. Allow it.


Finally, it will start to read the current temperature value for the given time period. Received temperature values are logged in a text box.


This application is in its early stages. If you need extra features etc. let us know please. It's already an open-source project on code.google.com site. Every body can help to develop it or write to us ...


The current temperature publishing page is like following: You need to replace some parts on the code. MySQL server, user and password,DB_name, table_name and "temp" field names should be changed manually.

Also you may want to sort the historical values by date, so I am adding a date field on the sample db.


<?php
$link = mysql_connect("MySQL_Server","MySQL_User","MySQL_Password") or die("Error message");

mysql_select_db("DB_Name") or die("Error message");

$query = "SELECT * FROM `table_name ORDER by `date` DESC";
$result = mysql_query($query);
$line = mysql_fetch_array($result);
$temp = $line["temp"];
print $temp;
mysql_close($link);
?>

You will get only the curreny temperature value as a plain text whenever the page is accessed by the TempAlarmer. Please let us know your comments to develop it more.

Have Fun!


Monday, October 31, 2011

Handling Plots with RCallerPhp Edition

Now we have RCaller Php edition, named RCallerPhp, which is able to handle images generated by R. I hope it will bring an other easy solution for calling R from other platforms.

With this feature, web developers that use Php as their main language and need calculations done by R will easly use this library.

It is distributed as its big brother, RCaller Java Edition, with the LGPL (Lesser GNU Public License).
RCallerPhp is intended to be compatible as much as possible with the Java version. So, investigating the old examples may be helpful for understanding this new release.

In a time of less than a week, we released this version without the plotting support. By now, generating R plots and showing them in a browser is implemented. Generated plots are stored in the temp directory instead www directory. That is why we are encoding generated plots inside the img src tags with base64 encoding. You can have a look at the source code at RCaller source code at Google project hosting.

Handling plots with RCallerPhp is quite easy. Let's have a look at the code below:

<?php

require_once("../RCode.php");
require_once("../RCaller.php");
require_once("simpletest.php");

$caller = new RCaller();
$code = new RCode("");

$plot = $code->startPlot();
$code->addRCode("plot.ts(rnorm(10))");
$code->endPlot();

$caller->setRscriptExecutable("/usr/bin/Rscript");
$caller->setRCode($code);
$caller->runOnly();

print($caller->getPlot($plot));
?>

Here is the generated output, which is copied from the web browser:


Nothing is easier than this! Do not hasitate to ask anything about RCaller.
We hope you enjoy...
Have fun...

Sunday, October 30, 2011

RCallerPhp is ready for testing

Hey web guys! RCaller now supports Php and we are planning to carry RCaller to other platforms and languages. The first step of our attack plan was to implement a Php edition and it is ready for testing now.

The second step is to implement RCaller for Perl and Python. We have now our Perl developer and he is in progress. Python is not our primary language and we are waiting for your helps. If you are familier with R and a developer of one of those languages below, join us. We are planning to carry RCaller to

  • Python
  • .Net
at first.

And... How it looks like.. Let's give up Java and speak Php for a minute:

 1 <?php
 2 include_once ("RCaller.php");
 3 
 4 $rcaller = new RCaller();
 5   $rcaller->setRscriptExecutable("/usr/bin/Rscript");
 6   $rcode = new RCode("");
 7   $rcode->clear();
 8   $rcode->addRCode("mylist <- list(x=1:3, y=c(7,8,9))");
 9 
10   $rcaller->setRCode($rcode);
11   $rcaller->runAndReturnResult("mylist");
12 
13   $x = $rcaller->getParser()->getAsStringArray("x");
14   $y = $rcaller->getParser()->getAsStringArray("y");
15 
16   echo ("X is <br>");
17   print_r ($x);
18 
19   echo ("<br><br>Y is <br>");
20   print_r ($y);
21 ?>


Waaav! Nothings changes! When you run this code, you will see values of x as 1, 2 and 3 and values of y as 7, 8, 9... The code above seems 100% compatible with the original library...

If you have used RCaller (Java edition) before, you will probably
understand the whole code. If not, lets have a look at the page RCaller 2.0 - Calling R from Java.


Note that, it is as in-efficient as the original version. Because RCaller creates external Rscript processes in each time RunAndReturnResult() thingies called. Be careful before using it in big and critical projects. Another note is about using it with too many users. RCaller uses temp directory to store its R codes and outputs. You need to clear this directory periodically. Otherwise you can have a "too many files" error.


Finally, source of is ready for use and development. Please visit the RCaller source code and downloads page. Php codes are stored as a separate project with name RCallerPhp.

Test it and do not hasitate to ask us!

Monday, October 24, 2011

For what the hell are we using Unity?

Last week, I upgraded my Ubuntu 11.04 to Ubuntu 11.10. This was a milestone in my Linux life.

In 2005, when I was a PhD student, my primary os was Windows XP. It was failing during the boot process but it was telling me nothing about the problem. I thought it was about one of the drivers but I was not the boss of my own computer. That was the reason to give it up and start with a new OS which gives the reins to me. It was Ubuntu, I don't remember the version but It should be 6 or 6.5.

Ubuntu was nice, easy to learn. As a hobbyist Java developer nothing changed by formatting the machine with ext3 and going on with the Gnome.

By the time, the community introduced more enhanced versions of Ubuntu. In each single revision, we get more happy to live with Ubuntu. The performance was perfect, there were lots of deb packages around and we got the chance of playing new games in our Linux boxes.

You know, Unity is the default GUI since Ubuntu 11.04. First time that I used that system, I tried to uninstall it and get the Gnome as soon as possible. In 11.10, I experienced the same thing and I saw that I can really get rid of it. Of course using XFCE or anything else should be the solution. But my problem is about the developer community.

First, why are you setting the Unity as default GUI system? Did people get bored with the GNOME desktop? Was it buggy? Have you performed a comprehensive survey about this?


Ubuntu with a Gnome Desktop is now a public good, because world is using it. People who wants to give it up can give it up. But I think it is wrong someone to make decisions about people use or not to use a GUI system by default...


Finally, I am finalizing the lifetime of Ubuntu in my boxes. The other distribution, Open Suse, seems to be more stable, say that, I am not afraid of being a dummy with my own computer. 


And, when you press Ctrl + Alt + 1 in your Linux Desktop, as you know, a full screen console will be opened. When you log in, you will see a "Have a lot of fun..." message in Open Suse 11. Yes, thank you. I am having fun right now!

Friday, October 21, 2011

Checking System Room Temperature with Cisco, Hp, Netscreen

{ able to visit following link to read newest entry about same subject;
This article has got a mobile phone client application to follow up to system room temperature. That first version is especially for Nokia Phones. }

The "http://stdioe.blogspot.com/2011/09/how-to-follow-up-temperature-of-system_23.html" article is explaining "How to follow up temperature of system room" via an IBM Blade Chassis device. I used to plan to explain how to use it because, the most reliable device on my system room is IBM Blade chassis. But may most of SDTIOE blog users haven't got an IBM blade chassis. Anyway that article can be able to help them ofcourse but I can re-write it for frequently used devices such as Cisco, Juniper and Hp. These products also have different operation systems. So each version has got little differences. This article presents some composite solutions for those systems.

Checking the system room temperature with Cisco:


Cisco routers have internaly got "show environment" or "show environment temperature" commands. We can get the temperature information with these commands. we can also use the article on page "http://stdioe.blogspot.com/2011/09/how-to-follow-up-temperature-of-system_23.html" to get that info from Cisco routers using the script below:

#!/usr/bin/perl

use Net::Telnet::Cisco;

my $session = Net::Telnet::Cisco->new(Host => 'x.x.x.x');
$session->login('TelnetUser', 'TelnetPassword');

# Execute a command
my @output = $session->cmd('show environment');
print @output;

$session->close;



attention!:
Cisco routers have different IOS versions and different IOS's have got different level of detail.

First Cisco example:

The first example is about Cisco 3661. It has got following IOS version;

HostName_Router_3661#show version 
Cisco Internetwork Operating System Software
IOS (tm) 3600 Software (C3660-IK9S-M), Version 12.2(13)T12, RELEASE SOFTWARE (fc1)
Technical Support: http://www.cisco.com/techsupport
Copyright (c) 1986-2004 by cisco Systems, Inc.
Compiled Tue 30-Mar-04 14:38 by ccai
Image text-base: 0x60008940, data-base: 0x61C20000

ROM: System Bootstrap, Version 12.0(6r)T, RELEASE SOFTWARE (fc1)
ROM: 3600 Software (C3660-IK9S-M), Version 12.2(13)T12, RELEASE SOFTWARE (fc1)

HostName_Router_3661 uptime is 7 weeks, 5 days, 11 hours, 21 minutes
System returned to ROM by reload
System restarted at 04:17:12 ISTANBUL Sat Aug 27 2011
System image file is "flash:c3660-ik9s-mz.122-13.T12.bin"

cisco 3660 (R527x) processor (revision 1.0) with 119808K/11264K bytes of memory.
Processor board ID JAC0617A0XT
R527x CPU at 225Mhz, Implementation 40, Rev 10.0, 2048KB L2 Cache
Channelized E1, Version 1.0.
Bridging software.
X.25 software, Version 3.0.0.
SuperLAT software (copyright 1990 by Meridian Technology Corp).
Primary Rate ISDN software, Version 1.1.
Basic Rate ISDN software, Version 1.1.


3660 Chassis type: ENTERPRISE
5 FastEthernet/IEEE 802.3 interface(s)
2 Serial network interface(s)
8 ISDN Basic Rate interface(s)
1 ATM network interface(s)
2 Channelized E1/PRI port(s)
2 Voice FXO interface(s)
2 Voice FXS interface(s)
DRAM configuration is 64 bits wide with parity disabled.
125K bytes of non-volatile configuration memory.
24576K bytes of processor board System flash (Read/Write)

Configuration register is 0x2102

HostName_Router_3661#


This IOS version supports only the "show environment" command and the output is simple. It hasn't got any value about the temperature as shown below:

HostName_Router_3661#show environment 

Power Supply 1 is present.
Thermal status: normal
Input Voltage status: normal
DC Output Voltage status: normal

Power Supply 2 is present.
Thermal status: normal
Input Voltage status: normal
DC Output Voltage status: normal

Board Temperature: normal.

HostName_Router_3661#


We have to grep the "Thermal status:" line and split it using the ":" character and get the usual part. The perl script should be changed for this goal as shown below:

#!/usr/bin/perl
use Net::Telnet::Cisco;
my $session = Net::Telnet::Cisco->new(Host => 'x.x.x.x');
$session->login('userName', 'passWord');
my @output = $session->cmd('show environment');

$session->close;

foreach $item (@output)
{
if(grep(/Thermal status/, $item) == "1") {
($key, $value) = split(/:/,$item);
}
}

sub trim($)
{
my $string = shift;
$string =~ s/^\s+//;
$string =~ s/\s+$//;
return $string;
}


$value = trim($value);
print "theValue:".$value."\n";

# If you want to write result to a file, you can use following part with erase "#" chars.

#open (target, ">tempfile.txt") || die ("Could not open file <br> $!");
#print target "$value";
#close (target);


We can do the parsing step in this Perl script or we can save the output of "show environment" command to a file and than handle it with shell commands. Lets try this way on "Second cisco example":

Second Cisco example:

The second example is about Cisco 38xx. It has got following IOS version;

HostName_Router_3800#show version 
Cisco IOS Software, 3800 Software (C3845-ADVIPSERVICESK9-M), Version 12.4(11)T3, RELEASE SOFTWARE (fc4)
Technical Support: http://www.cisco.com/techsupport
Copyright (c) 1986-2007 by Cisco Systems, Inc.
Compiled Wed 11-Jul-07 21:30 by prod_rel_team

ROM: System Bootstrap, Version 12.4(13r)T, RELEASE SOFTWARE (fc1)

HostName_Router_3800 uptime is 7 weeks, 4 days, 15 hours, 56 minutes
System returned to ROM by power-on
System image file is "flash:c3845-advipservicesk9-mz.124-11.T3.bin"


This product contains cryptographic features and is subject to United
States and local country laws governing import, export, transfer and
use. Delivery of Cisco cryptographic products does not imply
third-party authority to import, export, distribute or use encryption.
Importers, exporters, distributors and users are responsible for
compliance with U.S. and local country laws. By using this product you
agree to comply with applicable laws and regulations. If you are unable
to comply with U.S. and local laws, return this product immediately.

A summary of U.S. laws governing Cisco cryptographic products may be found at:
http://www.cisco.com/wwl/export/crypto/tool/stqrg.html

If you require further assistance please contact us by sending email to
export@cisco.com.

Cisco 3845 (revision 1.0) with 482304K/41984K bytes of memory.
Processor board ID FTX1135A1E0
4 FastEthernet interfaces
2 Gigabit Ethernet interfaces
1 Virtual Private Network (VPN) Module
DRAM configuration is 64 bits wide with parity enabled.
479K bytes of NVRAM.
125440K bytes of ATA System CompactFlash (Read/Write)

Configuration register is 0x2142 (will be 0x2102 at next reload)

HostName_Router_3800#


This IOS version supports only the "show environment" command but the output has higher level of detail when we compare it to "First Example". It has got temperature values as shown below:

HostName_Router_3800#show environment 

SYS PS1 is present.
Fan status: Normal
Input Voltage status: Normal
DC Output Voltage status: Normal
Type: AC
Thermal status: Normal

SYS PS2 is absent.

AUX(-48V) PS1 is present.
Status: Normal

AUX(-48V) PS2 is absent.
Compliance Mode: IEEE 802.af compliant

Fan 1 Normal
Fan 2 Normal
Fan 3 Normal

Fan Speed is Normal

Alert settings:
Intake temperature warning: Enabled, Threshold: 55
Core temperature warning: Enabled, Threshold: 70 (CPU: 90)

Board Temperature: Normal
Internal-ambient temperature = 31, Normal
CPU temperature = 42, Normal
Intake temperature = 24, Normal
Backplane temperature = 25, Normal

Voltage 1(3300) is Normal, Current voltage = 3316 mV
Voltage 2(5150) is Normal, Current voltage = 5153 mV
Voltage 3(2500) is Normal, Current voltage = 2525 mV
Voltage 4(1200) is Normal, Current voltage = 1215 mV

Nominal frequency

HostName_Router_3800#


We are interested in the temperature of system room, so we will use "Backplane temperature" part in this case. But other values are really very helpful for different purposes so you can edit this sample for something else like CPU. In this case, the Perl script records all of the output of "show environment" command to a file and we will handle that work using linux shell commands,

#!/usr/bin/perl
use Net::Telnet::Cisco;
my $session = Net::Telnet::Cisco->new(Host => 'x.x.x.x');
$session->login('userName', 'passWord');
my @output = $session->cmd('show environment');

$session->close;

open (target, ">tempfile.txt") || die ("Could not open file <br> $!");
print target "@output";
close (target);


Right now, all the information that we need is in the text file. We can handle it easily with linux shell commands. Lets continue,

grep "Backplane temperature" tempfile.txt | awk -F ' ' '{print $4}' | awk -F ',' '{print $1}'


The above result is 25 in this sample. We can use this final result as described on "http://stdioe.blogspot.com/2011/09/how-to-follow-up-temperature-of-system_23.html" article.

Checking system room temperature with Juniper / Netscreen:

Right now, I'm using an ISG2000 to prepare this article. The version information is;


Hardware Version: 3010(0)-(04), FPGA checksum: 00000000, VLAN1 IP (0.0.0.0)
Software Version: 6.1.0r3.0, Type: Firewall+VPN


We can use the following command to get the temperature information:

UGC:isg2000-UP(M)-> get chassis 
Chassis Environment:
Power Supply: Good
Fan Status: Good
CPU Temperature: 104'F ( 40'C)
Slot Information:
Slot Type S/N Assembly-No Version Temperature
0 System Board 0079082006000411 0051-005 E01 80'F (27'C), 84'F (29'C)
4 Management 0081082006000307 0049-004 D11 104'F (40'C)
5 ASIC Board 000319230H060098 0050-003 C00
Marin FPGA version 9, Jupiter ASIC version 1, Fresno FPGA version 102
I/O Board
Slot Type S/N Version FPGA version
1 2 port 10/100/1000T 0142092006000038 C00 20
3 2 port 10/100/1000T 0142092006000036 C00 20
4 4 port 10/100 0138082006000020 D01 6
Alarm Control Information:
Power failure audible alarm: disabled
Fan failure audible alarm: disabled
Low battery audible alarm: disabled
Temperature audible alarm: disabled
Normal alarm temperature is 132'F (56'C)
Severe alarm temperature is 150'F (66'C)
UGC:isg2000-UP(M)->


We can use the "|" (pipe) function to get required lines only. (Also This feature exists in Cisco. I try to write different solutions in each single example. But of course you can also use the pipe function in Cisco example.)

UGC:isg2000-UP(M)-> get chassis | include temperature
CPU Temperature: 104'F ( 40'C)
Slot Type S/N Assembly-No Version Temperature
Temperature audible alarm: disabled
Normal alarm temperature is 132'F (56'C)
Severe alarm temperature is 150'F (66'C)
UGC:isg2000-UP(M)->


This output is better, isn't it? Let's write a Perl script to get this info from the Juniper box to a file on our system.

#!/usr/bin/perl

use Net::Telnet::Netscreen ();

my $fw = new Net::Telnet::Netscreen(host=>'x.x.x.x');

$fw->login('username','password') or die $fw->error;

@lines = $fw->cmd("get chassis | include temperature");

open (target, ">tempfile.txt") || die ("Could not open file <br> $!");
print target "@lines";
close (target);


Now, we can use the content of tempfile.txt file. If you want to focus on only only a single line of this content, you can change "temperature" part on "get chassis | include temperature" command but It's not needed because, we can already manipulate that string with grep and awk commands.

Checking system room temperature with HP Procurve switch:

The first step is writing a Perl script to get the temperature information from Hp Procurve Switch. We can use a script as shown below:


#!/usr/bin/perl

use Net::Telnet ();
$session = new Net::Telnet (Timeout => 5,
Telnetmode => 0,
Prompt => '/PROMPTofDEVICE#/',
Host => "x.x.x.x");

# $session->waitfor('/Press any key to continue/');
# $session->print("");

$session->waitfor('/Password: /');
$session->print('PassworDofDevice');

$session->waitfor('/PROMPTofDEVICE#/');

@lines = $session->cmd("show system temperature");

$session->cmd("exit");
$session->cmd("exit");

open (target, ">tempfile.txt") || die ("Could not open file <br> $!");
print target "@lines";
close (target);


When we connect to a Procurve device, a "Press any key to continue" expression is shown. Some versions don't require this message to be shown. If you want this message to be shown, you can delete the '#' chars at the beginning of lines. The tempfile.txt file contains the information below:

 System Air Temperatures
# |Current Temp | Max Temp | Min Temp | Threshold | OverTemp
-------+-------------+----------+----------+-----------+----------
Sys-1 | 20C | 29C | 14C | 55C | NO


We can use a command as follows:

grep Sys-1 tempfile.txt | awk -F ' ' '{print $3}'


We can add that script to crontab and record output to mysql table. The other script/service can analyze recorded values like "http://stdioe.blogspot.com/2011/09/how-to-follow-up-temperature-of-system_23.html" article.