Showing posts with label Utility. Show all posts
Showing posts with label Utility. Show all posts

Tuesday, January 19, 2010

What an idea!

Yesterday i talked with an old friends! He helped me about finding a way to code "something". He is damn formal and accademic (and effective developers too), and i was so suprised on how two minds can works in sync.
So we started to chill around a lil project, which maybe we are gonna to develop...
The main was about "how to define an algorhythm as an XML documents". I guess we found a (maybe one of tons) solution an it is possible in the next days im gonna posting something more. It will be about BNF about a "certain" arguments, which will be translate as a XML-Scheme.
That scheme will be the data structure to work and interact with a web-based tool..
Nothing more, stay tuned..

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';
}

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;
}

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!!!!

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 ^^

Friday, March 13, 2009

Xiaolin wu circle php implementation



Gentle reader,
thank you for stumbling upon this old post. While it still lives here as a snapshot of the past, I’ve since moved to a new blog where I’m publishing updated and hopefully better-written content.

You can find the updated Xiaolin Wu article here.
Feel free to stop by I’d be glad to have you there.

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); ?>

Tuesday, November 4, 2008

Regex in markup

Well, in an older post (the italian one only) i made intensive use of regex to retrive HTML tags text content. Well, now i want to give you a simple trick to do this in a more elegant way.
Be careful: this post doesn't want to explain regex at all!
We all know that a markup tag with a content look like <tag_name>content</tag_name>.
Well to retrive the content we only need to match everything between tag_name, we match it as:
"everything tat is not the character 'less than'".
So the regex look like: /<tag_name>([^<]+)<\/tag_name>/

here a php interactive session:

Interactive shell

php > $string = "<tag_name_one>http://tag_name_one.com</tag_name_one><tag_name_two>123 ## @ jhkasdfh</tag_name_two>";
php > $tag_name = "tag_name_one";
php > $result = array();
php > preg_match("/<$tag_name>([^<]+)<\/$tag_name>/", $string, $result);
php > print_r($result);
Array
(
[0] => <tag_name_one>http://tag_name_one.com</tag_name_one>
[1] => http://tag_name_one.com
)
php > $tag_name = "tag_name_two";
php > preg_match("/<$tag_name>([^<]+)<\/$tag_name>/", $string, $result);
php > print_r($result);
Array
(
[0] => <tag_name_two>123 ## @ jhkasdfh</tag_name_two>
[1] => 123 ## @ jhkasdfh
)

Thursday, October 9, 2008

Numeri di telefono on the fly

NB: Italian only, this script is useful for italian only readers. This script recive as input an italian phone number and give its holder as output.

In questo post vediamo come ricavere on the fly informazioni su intestatari di numeri di telefono.

Si tratta di due scritp pensati per essere eseguiti direttamente dall'interprete php.

Può essere utile in ufficio sapere in anticipo chi sta telefonando e consultare il sito delle pagine bianche può risultare un dispendio di tempo. Questi script si occupano di interrogare il sito delle pagine bianche fornendo un numero di telefono; se questo è presente nell'elenco verrà visualizzato nella shell evitando i tempi di attesa del browser.

Gli script si servono della libreria curl, quindi è necessario averla propriamente installata sulla propria macchina.

Grazie alla curl, lo script interroga lo script delle pagine bianche incaricato di restituire il numero di telefono; ricevono in risposta il codice html che verrebbe normalmente visualizzato nel broswer. A questo punto il comportamento degli script è differente. Uno ricava i dati servendosi di regex; l'altro istanzia due oggetti: un DOMDocument e un DOMXPath; i dati vengono ricavati con query xpath.

La pagina di risposta delle pagine bianche formatta i dati all'interno di tag che (salvo grosse modifiche alla pagina!!) sono sempre gli stessi;, in questo modo è possibile ricavare i dati. Vediamo il codice degli script, tenendo presente che grosso modo la performance è praticamente identica.

pagine_bianche_regex.php

if($argc != 2) die("Parametro necessario: Numero di telefono\nNon devono essere presenti spazi all'interno del numero.\n\n");
$tel = $argv[1];
$url = "http://www.paginebianche.it/execute.cgi?btt=1&ts=106&cb=8&l=it&mr=10&rk=&om=&qs=$tel";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$out = curl_exec($ch);
$m = array();
$test = preg_match('/<h3 class\=\"org\">([a-zA-z\s]+)<\/h3>/',$out, $m);
echo "\n\t$tel";
if($test == 0) die("\n\tNumero Non Trovato\n\n");
echo "\n\tIntestatario/a: ".$m[1]."\n";
preg_match('/<span class="postal\-code">([0-9]+)<\/span>/', $out, $m);
echo "\tIndirizzo: ".$m[1]." ";
preg_match('/<span class="locality">([a-zA-z\s]+)<\/span>/', $out, $m);
echo $m[1]." ";
preg_match('/<span class="region">\(([A-Z]{2})\)<\/span>/', $out, $m);
echo $m[1]." ";
preg_match('/<span class="street\-address">([A-Za-z\s0-9,]+)<\/span>/', $out, $m);
echo $m[1]."\n\n";
curl_close($ch);

pagine_bianche_xpath.php

if($argc != 2) die("Parametro necessario: Numero di telefono\nNon devono essere presenti spazi all'interno del numero.\n\n");
$tel = $argv[1];
$url = "http://www.paginebianche.it/execute.cgi?btt=1&ts=106&cb=8&l=it&mr=10&rk=&om=&qs=$tel";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$out = curl_exec($ch);
$html = DOMDocument::loadHTML($out);
$xp = new DOMXpath($html);
echo "\n\t$tel";
$data = $xp->query("//h3[@class=\"org\"]");
if($data->length == 0) exit("\n\tNumero Non Trovato\n\n");
echo "\n\tIntestatario/a: ".$data->item(0)->nodeValue;
$data = $xp->query("//span[@class=\"postal-code\"]");
echo "\n\tIndirizzo: ".$data->item(0)->nodeValue;
$data = $xp->query("//span[@class=\"locality\"]");
echo " ".$data->item(0)->nodeValue;
$data = $xp->query("//span[@class=\"region\"]");
echo " ".$data->item(0)->nodeValue;
$data = $xp->query("//span[@class=\"street-address\"]");
echo " ".$data->item(0)->nodeValue."\n\n";
curl_close($ch);