Tuesday, November 3, 2009

Bluetooth Device Discovery in c language HOW TO

Today i wanna show a simple how to about bluetooth programming.
I will start witha brief theory follow by a full commented c source compile under linux.

This two functions convert a string address in a bdaddr_t (a defined structure which is a bluetooth device address) and viceversa
str2ba (const char * str , bdaddr_t * ba)
ba2str (const bdaddr_t * ba , char * str)
We also need to know about local bluetooth adapter, this functions will be useful:
int hci_get_route (bdaddr_t * addr)
Return the device id of the given bdaddr_t, you can pass NULL so it returns the first available device.
If you know the device's address you want to use you can pass it to this function
int hci_devid (const char * addr)
finally you can open resources to use the device you choose with
int hci_open_dev (int adapter_id)
Now you need to send an inquiry signal to receive information about the devices to respond.
You can do this by calling
int hci_inquiry (int adapter_id, int len, int max_rsp,
 const uint8_t * lap , inquiry_info ** devs , long flags
)
  • adapter_id = the adapter you choose before
  • len = inquiry time, the standard is about 8 * 1.24 (so len = 8)
  • max_rsp = maximum devices response (usually 255)
  • flags = usually IREQ CACHE FLUSH, if you pass 0 then previous inquiry info may be returned
  • lap = determine the type of inquiry, if you don't care give it NULL.
Be careful: devs parameter should be sized enough to store a max of max_rsp inquiry_info struct...
Sounds like:
(inquiry_info *)malloc (max_rsp * sizeof (inquiry_info));
And finally you can get devices friendly name, follow this how-to
  1. cycle hci_inquiry return step to check for the devices found
  2. look for bdaddr_t field in the devices list stored by hci_inquiry, converted by ba2str
  3. store enough memory to convert string address to string name
  4. get the name with:
    int hci_read_remote_name (int hci_sock, const bdaddr_t * addr,
     int len, char * name, int timeout)

And here the code:
/**
 * bdd_main.c
 *
 * This is a sample about how to discovery bluetooth device
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/hci.h>
#include <bluetooth/hci_lib.h>

int main (int argc, char ** argv)
{
 inquiry_info * devices = NULL; // This struct will store the found devices
 int max_rsp, num_rsp; // max devices to find, devices found
 int adapter_id, sock, len, flags; // use to hci_inquiry and hci_open_dev, returned by hci_open_dev, 1.24 * len sec inquiry time, flags chache or flush
 int i;
 char addr[19] = { 0 }; // this is a middle to find out friendly name
 char name[248] = { 0 }; // this is to store friendly name

 /* OPEN A LOCAL BLUETOOTH ADAPTER */
 adapter_id = hci_get_route(NULL);
 sock = hci_open_dev(adapter_id);
 if(adapter_id < 0 || sock < 0)
 {
  fprintf(stderr, "Error code %d: %s\n", errno, strerror(errno));
  exit(1);
 }

 /* INQURY PROCESS */
 len = 8; // 10.24 sec lasts
 max_rsp = 255; // max of 255 devices to discover
 flags = IREQ_CACHE_FLUSH; // no use previous inquiry data
 devices = (inquiry_info *)malloc(max_rsp * sizeof(inquiry_info)); // malloc for devices

 num_rsp = hci_inquiry(adapter_id, len, max_rsp, NULL, &devices, flags); // inquiry
 if(num_rsp < 0)
 {
  fprintf(stderr, "Error code %d: %s\n", errno, strerror(errno));
  exit(1);
 }

 /* FRIENDLY NAME */
 for(i = 0; i < num_rsp; i++)
 {
  ba2str(&(devices+i)->bdaddr, addr); // convert bdaddr to a string
  memset(name, 0, sizeof(name)); // memset to store friendly name
  if(0 != hci_read_remote_name(sock, &(devices+i)->bdaddr, sizeof(name), name, 0)) // store in name the first sizeof(name) byte of the friendly name of the given addr.
  {
   // this mean the friendly name was not found
   strcpy(name, "[unknow]");
  }

  printf("%s %s\n", addr, name);
 }

 /* ENDING ROUTINES */
 free(devices);
 close(sock);

 return 0;
}

Do not forget to compile linking bluetooth lib XP...

Saturday, October 24, 2009

Eclipse 3.5 SR1 Galileo (C/C++ IDE) devkitpro on Linux Mint 7

Im trying different enviorment on which devel. Today i wanna keep information i found on how to set up an linux eclipse c/cpp IDE for nintendo DS programming. Especially this work for Linux Mint 7 but i guess this should work for most linux distros.

If you try to install eclipse for c/cpp from mintInstall you will notice that it is an older version, which is not compatible with an interesting plugin:
NDS Managedbuilder
.

So the way you have to follow is to download the latest eclipse version from the official site.
Well you love to do it all by shell, so open up your terminal, look on the web the download link and get it.
Now you need to extract it everywhere you want in your filesystem. I dowload it in my home folder and extract in /opt/

~ $ wget <link>
~ $ tar -C /opt/ -xvjf <archivename>


And about eclipse it's all. You can launch it from there or link it eveywhere you want.

the latest link is: http://www.eclipse.org/downloads/download.php?file=/technology/epp/downloads/release/galileo/SR1/eclipse-cpp-galileo-SR1-linux-gtk.tar.gz.

Now we will move on the devkitpro getting started web-site. There is deeply and clearely explained how to install the toolchain.
It's easy, just build the filesystem tree, download the libraries and extract in the right folder.
You can finde the wiki here: devkitARM.

Well it's time to install the eclipse plugin so move to NDS Managerbuilder, open eclipse

Help > Install New Software > click "Add" button > http://dev.snipah.com/nds/updater

follow the instruction, restart eclipse and you are ready to develop for Nintendo DS (c/cpp too) on eclipse in a linux enviorment!

[EDIT] Stay tuned, gonna look to add PAlib too ;)

Tuesday, October 13, 2009

c Kernighan & Ritchie exercise

Lately im into c programming, really newbie, so im reading Kernighan & Ritchie famous book.
Here a funny exercise that reverse an input line string:

"Write a function reverse(s) that reverses the character string s. Use it to write a program that reverses its input a line at a time."

i change the params as you can see..


#include <stdio.h>

#define MAXLEN 30

int getline(char s[], int lim);
void reverse(char s[], char r[], int len);

int main()
{
int len;
char line[MAXLEN];
char reversed[MAXLEN];

len = 0;

while((len = getline(line, MAXLEN)) > 0)
{
reverse(line, reversed, len);
printf("\nReversed = %s\n\n", reversed);
}

return 0;
}

int getline(char s[],int lim)
{
int c, i;
for (i=0; i < lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
s[i] = c;
if (c == '\n') {
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}

void reverse(char s[], char r[], int len)
{
int i;

for(i = 0; i < len; i++)
r[i] = 0;

for(i = 0; i < len; i++)
{
/* -2 will strip \n in the original string (-1 the original end of string */
r[i] = s[len-i-2];
}
r[len] = '\0';
}

Monday, October 5, 2009

Devkitpro 1.5.0, PAlib and Visual c++ 2008 Express

Few days ago i started to think about devkitpro, to develop nintendo DS homebrew software. So i start to chill around PAlib. Just to check out. So i move to the wiki to installing the toolchain.
I soon discover that it was possible to use PAlib with Visual c++ 2008 Express.
I notice that the step to follow was outdated.

If you want to get it work just follow that steps but with this difference:

  1. Set PAPATH enviorment variable to this one: <path to devkitpro>/PAlib/lib

  2. After the launch of the PAlib application wizard, change the makefile inside <path to PAlib application wizard>/Files/Templates/1033 with one you can find in the PAlib examples

  3. If you want to keep logos inside the data folder change the icon path in the make file from ICON := -b $(CURDIR)/../logo.bmp to ICON := -b $(CURDIR)/../data/logo.bmp

that's all, this work fine, hope someone could find this useful.

Thursday, September 10, 2009

PHP directory listing : convert a folder tree into an array

Hi there!

in a post few months ago i talked about Directory listing in php, there i show a pair of function to list a directory and turn it into an array.

Well today i come back to that function and change it a little to get it better.

It's quite simple, it start from a path (btw thinking correct) and push it into a structured array. In wich every array element mean a subdirectory, and a null value mean a file.

You can choose the recursive mode in which, when a subfolder is found goes deep into it (recursively too) to fill the array with file and subfolder of that directory.

It's simple, it just check the params $recurrent for true and that the "entry" scaned by read method from metaclass dir is a directory.

Hope someone could find it useful.


function array_converter($path, $recurrent = false, $tree = array())
{
$path = realpath($path);
$d = dir($path);
while(false != ($entry = $d->read()))
{
$complete = $d->path."/".$entry;
if(is_dir($complete) && $entry !== '.' && $entry !== '..')
{
$tree[$entry] = array();
if($recurrent && $entry !== '.' && $entry !== '..')
{
$tree[$entry] = array_converter($complete, $recurrent, $tree[$path][$entry]);
}
} elseif($entry !== '.' && $entry !== '..') {
$tree[$entry] = null;
}
}
$d->close();
return $tree;
}

Wednesday, September 9, 2009

Silence please, one minute: Mike Bongiorno

Too much to say,

you are great, the most! You change our point of view, you win on TV.

Thanks Mike, so much.

Allegria!

Tuesday, September 1, 2009

PHP RESTful WebService

Lately im working on a restful php webservice.
In its concepts RESTful is quite easy, but it is still not really understand by most of web programmers.

So if you are interested, first of all you should start to study what behind REST, so its architecture. Good resources are of course wikipedia and Roy Thomas Fielding's dissertation which start the most of works.

Then you may try to develop, or study already coded RESTful web service, the most comes from ruby and python programming languages. Im quite sure to be blind, but in the end i really didn't find goods PHP resources about RESTful (genuine RESTful i mean!) from surfing the web.

The really best i found is an article signed by Gareth Jones: Building a RESTful Web application with PHP and it's starting point lornajane.

A really good book (which i found such likes a REST bible) is RESTful Web Service, written by Leonard Richardson and Sam Ruby.

I know it's a lot of things, this is the RESTful price to pay!

But it's good, trust me people!

Friday, July 31, 2009

Google translate simple php client

This morning i were reading an english based blog. I came from italy and (as you can notice) im not the best english speller at all. Sometimes i need to use an online dictionary to translate words or sentences. One of the most dictionary translation is wordreference.com and also http://translate.google.com/.
Well im a web programmer, google offers a rich api to its services, so i thought to write a really simple php batch to translate words or simple sentence.

here a snippet:


<?

if($argc < 4) die("usage: gt.php \"sentence\" <start lang> <translation lang>");

$sentence = urlencode($argv[1]);
$start = $argv[2];
$arrive = $argv[3];

$url = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=$sentence&langpair=$start%7C$arrive";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, "http://www.google.com/");
$body = curl_exec($ch);
curl_close($ch);

$json = json_decode($body);

if(!is_null($json->responseDetails)) { die($json->responseDetails); }

echo $json->responseData->translatedText;

Hope someone could find this useful. You can call it as the follow:
gt.php "sentence or words" <strat> <translate>

Have fun =) !

Thursday, July 9, 2009

Directory listing in PHP

[edit] i write a new function: PHP directory listing : convert a folder tree into an array [/edit]

Hello world!

Lately im working on a series of tools which can be useful to organize works in web. Of course, nothing new, but im developing somthing mine and small that i can overwork instead of more complex tools.

This run for web of course and my interest is about:
  • deploy
  • backup
  • maintenance
Well about deploy i actually don't know what i want.
Backup it's what im working at.
maintenance i mean a simple tool that switch web-sites/single page in maintenance or work.

About Backup:
I first thought at a tool for a full and incremental backup, but in the end i decided to add the possibility to manage backup as project, saving status about multiple projects. Im currently working and the first piece of code i will give you is a pair of functions that help you to list directories recursively (and turn it into a PHP array.

function create_tree ($path) {
if(is_dir($path)) {
$tree["$path"] = array();
$tree = get_tree($path, $tree);
return $tree;
} else {
echo "<$path> is not a directory";
exit;
}
}

function get_tree($path, $tree) {
$dir = dir($path);
while(false !== ($entry = $dir->read())) {
$complete = "$path/$entry";
if(is_dir($complete) && $entry != "." && $entry != "..") {
$tree["$path"]["$entry"] = get_tree($complete, $tree[$path][$entry]);
} elseif($entry != "." && $entry != "..") {
$mod = date('d-m-Y H:i:s', filemtime($complete));
$tree[] = array( "fn" => $entry, "mod" => $mod);
}
}
return $tree;
}
And that is that, as you can see when it adds a new entry into the array it save last modification time too, sure will be useful to incremental backup.

TODO: pretty print!!!!

Tuesday, July 7, 2009

it's a rainy day

Milan.. a rainy day.. what happen???

KERNEL PANIC!

Wednesday, April 1, 2009

MySql Table to HTML Table

Hi to all!!

happy april :p like CADIE?

Well now i want to exctract a little preview form dbi that should be useful to someone.

This is a php function and could needed to be a little change from you. in_table function print out a HTML table showing the results of a SELECT query. Actually the function (as it is) need an existent mysql connection and the function mysql_select_db() already called. Then you could add classes to HTML Table element to style as you want.

All the game is based on mysql_fetch_assoc() and array_keys(). It first execute the query (without security check =P) then while cycle result with mysql_fetch_assoc(); then check an internal counter with a value as modulus to "decide" if print headers again or not (headers is the field name or their aliases).
Here the function:

function in_table($query, $repeat = 50) {
$result = mysql_query($query);
if(!$result) {
echo "Error: ".mysql_error();
die();
}
$counter = 0;
echo "<table>";
while($data = mysql_fetch_assoc($result)) {
echo "<tr>";
if($counter % $repeat == 0) {
$fields = array_keys($data);
foreach($fields as $field)
echo "<th>$field</th>";
echo "</tr><tr>";
$counter = 0;
}
foreach($data as $val)
echo "<td>$val</td>";
echo "</tr>";
$counter++;
}
echo "</table>";
}


Here a little snapshoot about the output ^^

Tuesday, March 31, 2009

Latest updates 2

Dear readers,

actually im working on improve this args:


It should be nice to turn the schema into EBNF as another final example!

have a nice day!

Friday, March 13, 2009

Xiaolin wu circle php implementation

In this post i will finally close this works: Xiaolin Wu look like circle.

Here the function wu_cirlce (helped by distance() and new_color()) that plot an antialiased circle. You need GD supports, the params are commented. Hope this could help someone:


<?php
/*
@author mauro p
*/
function distance($r, $y) {
$real_point = sqrt(pow($r, 2) - pow($y, 2));
return ceil($real_point) - $real_point;
}

function new_color($i) {
return round(($i * 127));
}

/**
* $image a gd image resource
* $r circle's radius
* $color rgb array like array('red' => int(0 : 255), 'green' => int(0 : 255), 'blue' => int(0 : 255))
* $offset_x x axis circle's center
* $offset_y y axis circle's center
*/
function wu_circle($image, $r, $color, $offset_x = null, $offset_y = null) {
$red = $color["red"];
$green = $color["green"];
$blue = $color["blue"];
$offset_x = (is_null($offset_x)) ? 0 : $offset_x;
$offset_y = (is_null($offset_y)) ? 0 : $offset_y;
$x = $xx = $r;
$y = $yy = -1;
$t = 0;
$color = imagecolorallocate($image, $red, $green, $blue);
while($x > $y) {
$y++;
$current_distance = distance($r, $y);
if($current_distance < $t) {
$x--;
}

$trasparency = new_color($current_distance);
$alpha = imagecolorallocatealpha($image, $red, $green, $blue, $trasparency );
$alpha2 = imagecolorallocatealpha($image, $red, $green, $blue, 127 - $trasparency);
imagesetpixel($image, $x + $offset_x, $y + $offset_y, $color);
imagesetpixel($image, $x + $offset_x - 1, $y + $offset_y, $alpha2 );
imagesetpixel($image, $x + $offset_x + 1, $y + $offset_y, $alpha );

imagesetpixel($image, $y + $offset_x, $x + $offset_y, $color);
imagesetpixel($image, $y + $offset_x, $x + $offset_y - 1, $alpha2);
imagesetpixel($image, $y + $offset_x, $x + $offset_y + 1, $alpha);

imagesetpixel($image, $offset_x - $x , $y + $offset_y, $color);
imagesetpixel($image, $offset_x - $x + 1, $y + $offset_y, $alpha2);
imagesetpixel($image, $offset_x - $x - 1, $y + $offset_y, $alpha);

imagesetpixel($image, $offset_x - $y, $x + $offset_y, $color);
imagesetpixel($image, $offset_x - $y, $x + $offset_y - 1, $alpha2);
imagesetpixel($image, $offset_x - $y, $x + $offset_y + 1, $alpha);

imagesetpixel($image, $x + $offset_x, $offset_y - $y, $color);
imagesetpixel($image, $x + $offset_x - 1, $offset_y - $y, $alpha2);
imagesetpixel($image, $x + $offset_x + 1, $offset_y - $y, $alpha);

imagesetpixel($image, $y + $offset_x, $offset_y - $x, $color);
imagesetpixel($image, $y + $offset_x, $offset_y - $x - 1, $alpha);
imagesetpixel($image, $y + $offset_x, $offset_y - $x + 1, $alpha2);

imagesetpixel($image, $offset_x - $y, $offset_y - $x, $color);
imagesetpixel($image, $offset_x - $y, $offset_y - $x - 1, $alpha);
imagesetpixel($image, $offset_x - $y, $offset_y - $x + 1, $alpha2);

imagesetpixel($image, $offset_x - $x, $offset_y - $y, $color);
imagesetpixel($image, $offset_x - $x - 1, $offset_y - $y, $alpha);
imagesetpixel($image, $offset_x - $x + 1, $offset_y - $y, $alpha2);

$t = $current_distance;
}

return $image;
}

$image = imagecreatetruecolor(500, 500);
$c = array("red" => 255, "green" => 0, "blue" => 255);

$image = wu_circle($image, 50, $c, 150, 150);

header('Content-type: image/png');
imagepng($image);
imagedestroy($image);


the result:

Tuesday, March 10, 2009

MySql Database Inspector

Well, came back,
im very busy lately so my posts as you can see, decrease in number. Now i want to start in a new project (lol added to the lot i've already started). It's about mysql database, a simple web application that only show all databases structure in a web browser.

You need to download jquery to let it works.

The workflow is easy: it first put in a multidimensional php array all the information
array[dbs_name][tables_name][fields_name] = field_type.
then create div inside div to graphically render the structure, helped by jquery and putting information out with php.

In the future should be interesting improving it by adding a query box that helps the user in building the query by selecting the type of the query and filling it by clicking on the graphically structure, and obviously manually filling too.

Here the code:
"db_struct.php"
This file contains the function get_structure($mysql_connection_resource) which convert the databases into the array.

function get_structure($conn_res) {
$resdbs = null;
$restbls = null;
$resclmns = null;
$resdbs = mysql_list_dbs($conn_res);
$structure = array();

while($dbs = mysql_fetch_object($resdbs)) {
$dn = $dbs->Database;
$restbls = mysql_list_tables($dn, $conn_res);
while($tbls = mysql_fetch_array($restbls)) {
$tn = $tbls[0];
$resclmns = mysql_list_fields($dn, $tn, $conn_res);
$result = mysql_query("SHOW COLUMNS FROM $tn");
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$fn = $row['Field'];
$structure["$dn"]["$tn"]["$fn"] = $row["Type"];
}
}
}
}
return $structure;
}


"web gui"
This file is the web render. You need to put your connection data and a link to jquery (i used 2.6)
<?
require_once "db_struct.php";
$conn = mysql_connect("yourhost", "youruser", "yourpass");
$s = get_structure($conn);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script type="text/javascript" src="jquery_source"></script>
<style>
#main {
width: auto;
}
.database {
float: left;
border: 1px solid darkred;
background: #CCCCCC;
margin: 5px;
padding: 2px;
width: 300px;
overflow: auto;
}
.table {
border: 1px solid darkgreen;
background: #DDDDDD;
margin-bottom: 4px;
padding: 3px;
width: 280px;
overflow: auto;
}
.field {
border: 1px solid darkblue;
background: #EEEEEE;
margin-bottom: 2px;
padding: 2px;
width: 260px;
overflow: auto;
}
span {
font-weight: bold;
}
span.Db {
color: darkred;
font-size: 150%;
}
span.Tb {
color: darkgreen;
font-size: 130%;
}
</style>
</head>
<body>
<div class="closer">
<p>Collapse: </p>
<button id="cdb">All DBS</button>
<button id="ctb">All TBS</button>
<button id="cfd">All FDS</button>
</div>
<div id="main"></div>
<script type="text/javascript">
var main = $("#main");
<? foreach($s as $db => $tbls): ?>
var td = $("<div>");
td.html("<span class='Tit Db'><?= $db ?></span>");
td.addClass("database");
<? foreach($tbls as $tbl => $flds): ?>
var tt = $("<div>");
tt.html("<span class='Tit Tb'><?= $tbl ?></span>");
tt.addClass("table");
<? foreach($flds as $fld => $type): ?>
var tf = $("<div>");
tf.html("<i><?= $fld ?></i> : <?= $type ?>");
tf.addClass("field");
tt.append(tf);
<? endforeach; ?>
td.append(tt);
<? endforeach; ?>
main.append(td);
<? endforeach; ?>
$("#cdb").click(function() {
$(".database").toggle();
});
$("#ctb").click(function() {
$(".table").toggle();
});
$("#cfd").click(function() {
$(".field").toggle();
});
</script>
</body>
</html>
<? mysql_close($conn); ?>

Wednesday, February 4, 2009

Latest Updates

Well here some updates i've done lately about older posts:


  • Web-related Drag theory
    Prettify the code =) in the next future i will working on keep the div exactly where the mouse is clicked.


  • Bakus-Naur Form
    Added two examples. The first one is easy and show how to define a little subset of a natural language, such as an affermative sentence. The second one a little more complex define rules with recursion, it want to define rules to create a string useful to represents a Mysql linking table.
    Added few rows about Extended Backus-Naur Form.


I am also working on a new version of Xiaolin wu Antialias. My goal is to define a PHP5 class to draw antialised circles and lines.

Have a nice day!

Monday, February 2, 2009

Social Network

Real life



... Is everything you could taste on your skin, everything could make you happy or worry, everything make you cry for happines or sadness. Everything let your heart beat fast or stop to beat at all. That's what i mean.


DigiLife



Digital life is a series of signal, nothing more... Digital life comes from a machine, a personal computer or everything like that. and it is only for support at your Real Life!


Misjudged



Sometimes, often lately, i discover too much people haze the line between digilife and real life.. And it's no good. Think it out, few minutes: are you driving away from real life? it is the solution?
Web and digital should help your real life and not shadow it!

Wednesday, January 28, 2009

XML Schema for Charting - a first implementation


<?xml version="1.0"?>

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="LineChart" type="line_chart"/>

<xs:complexType name="line_chart">
<xs:all>
<xs:element name="LineChartInfo" type="chart_info" />
<xs:element name="Points" type="points_" />
</xs:all>
</xs:complexType>

<xs:complexType name="chart_info">
<xs:all>
<xs:element name="ChartHead" type="xs:string"/>
<xs:element name="width" type="chart_measure"/>
<xs:element name="height" type="chart_measure"/>
<xs:element name="xSpace" type="xs:integer"/>
</xs:all>
</xs:complexType>

<xs:complexType name="points_">
<xs:sequence>
<xs:element name="Point" type="point_" minOccurs="2" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>

<xs:complexType name="point_">
<xs:all>
<xs:element name="Label" type="xs:string"/>
<xs:element name="Action" type="xs:string"/> <!-- ENUM -->
<xs:element name="x" type="xs:integer"/>
<xs:element name="y" type="xs:decimal"/>
</xs:all>
</xs:complexType>

<xs:simpleType name="chart_measure">
<xs:restriction base="xs:integer">
<xs:minInclusive value="100"/>
</xs:restriction>
</xs:simpleType>
</xs:schema>


This is just a start, my idea is to first provide information about the chart (a line chart in this test), that should be useful to the xml stylesheet transformation (for example: width and height to set in the svg, head to titled the chart, xspace tell us how much pixel separate every x point).
Then every Point element set x, y for each point and its label.
Soon a new version and the xsl to test it =). And then of course more extensive explanation on this and the older post.
So.. stay tune again !

Tuesday, January 13, 2009

Backus-Naur Form

Backus-Naur form, is a way to describe grammar for programming languages, communication protocols, instruction set and to represent part of natural language too. It express free context grammar.
A BNF consist of a set of derivation rules, made of symbols. Every Symbol is expressed as a rule like:
<symbol> ::= expression
an expression could be another symbol or a choice of symbols separated by a vertical bar. On the right side a symbol could be a terminal symbol or a non-terminal symbol. A terminal symbol is a symbol which never appears on the left side. When you find a non-terminal symbol on the right side you have to exchange it with its expression, at the end of the chain you are going to find a terminal symbol you can use :).
Starting from the first definition to the terminals symbol definition you could "write" everything could be expressed by that BNF.

See also:
BNF on wiki
PHP source [you can find the EBNF in the source]

In the next post im going to tell you how i write an xsd (XML Scheme) about XML syntax in order to transform it into graph by a XSLT.
Enjoy!

UPDATE:
At the begin, the acronym BNF meant Backus Normal Form, but later decided to use Naur instead of Normal in honour of Peter Naur a member of the Algol committee.
The most "popular" variant of BNF is absolutely EBNF (Extended Backus Naur Form which introduce optional repeatable (group) of symbols.

UPDATE:
Some examples in order to understand how BNF works.

In italian language, the structure of an affermative sentence in simple present sounds (also) like:
Subject + verbs + subject
We define subject as: Article + noun
In english sounds the same, so a sentence in that way could be: "The child eats candies".
Well, let's try to derive a BNF that express that simple rule

<Affermative Sentence> ::= <Subject> <Verbs> <Subject>
<Verbs> ::= 'all the simple present verb these are all terminal symbols!'
<Subect> ::= <Article> <Nouns>
<Article> ::= The | A | An
<Nouns> ::= 'all the nouns, these are all terminal symbols!'

If you start from the root <Affermative Sentence> and substitute element's with it's definition, in the end you should get an affermative simple present sentence. Of course, we should extend the definition in order to explain when to use "The" instead of "A" or "An", but this BNF is just to let you understand how it works.
Here you can find EBNF definition on wiki, it's a very good entry, so check it out!

An other more complex example:
Now we are going to discover the power of BNF syntax. We want to write rules for a string which built a SQL insert query. A query for a link table:
Table 1 -> link table <- Table 2 (N:N)
This will be the form:
List of comma separated ids ended by ';'; every list are follow by an id and ':'. The ids before ':' comes from table 1, the comma separated id from table 2
Strings like:
1:3,4,5;33:2,31,13;4:77;
OR
245:23;
And so on.

<Query Block> ::= <Table id> <Table Separator> [<Single Table List>] <Closer Table List> | <Query Block>
<Single Table List> ::= <Table id> <Separator> | <Single Table List>
<Closer Table List> ::= <Table id> <Closer>
<Table id> ::= <Digit> | <Table id>
<Digit> ::= '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | '0'
<Table Separator> ::= ':'
<Separator> ::= ','
<Closer> ::= ';'

sentence inside square brakets mean the sentence is optional!
In the next day im going to post another example.
Have a nice Day!

Monday, January 12, 2009

XML and Graph

Since i knew xml like languages i was impressed. Lately im thinking about take a new look to some of that languages to start a new little project (as always i will be share on here).
Yes, the title talk about graph, in real i don't really care about graph, but i want to improve my xml like languages knowledge with graph as a pretext.

My goal is to define an XML Schema that that lead a graph definition and thanks to a XSL transformation render the graph into a the browser as a SVG.

About me it sounds cool!

So the next steps are:

  1. Define a XML Schema (and way not talk about EBNF)

  2. 2) Define the XSL transformation

  3. Hope it works =) !



Stay tune, i will talk about XML Schma and EBNF in the near future.