Posted by: thiagoribeiro | 2011/03/01

Simple pie chart with HTML5

I needed to use some charts in my system, so I’ve decided to code something in HTML5 and to pass all dirty processing job to the user navigator.

After reading a little about canvas object, I got this code below:

$(document).ready( function() {
	var getColors = function( total ) {
		var r,g,b = 0;
		var colors = new Array();

		for( var i = 0; i < total; i++ ) {
			r = Math.abs(Math.floor(Math.random()*254));
			g = Math.abs(Math.floor(Math.random()*254));
			b = Math.abs(Math.floor(Math.random()*254)); 

			colors[i] = 'rgb('+r+','+g+','+b+')';
		}

		return colors;
	};

	var graph = function(obj, width, height, values, colors) {
		if( values.length == 0 && $('#'+obj).attr('id') == '' ) {
			return false;
		} else {
			var canvas = $('#'+obj)[0];

			if( !canvas.getContext ) {
				alert('Problem to load canvas, try moving your javascript code before ');
				return false;
			}
		}

		var total = 0;
		var percent = [];

		for(var i in values) {
			total += values[i];
		}

		if( typeof(colors) != 'object' && !(colors instanceof Array) ) {
			var colors = [];
			colors = getColors(values.length);
		}

		canvas.width = width;
		canvas.height = height;
		var context = canvas.getContext('2d');
		var angle_start = 0;
                var angle_end = 0;
		var point = [width/4, height/2];
		var pointradius = [width/2, height/2];
		var legend_x = pointradius[0]+((5*100)/width);
		var legend_y = pointradius[1] - height/7;
		var rect_size = (30*100)/width;
		var radius = Math.min( pointradius[0], pointradius[1] ) / 1.2;

		for(var i in values) {
			percent[i] = values[i] * 2 / total;
			angle_end += percent[i];
        	        context.beginPath();
			context.arc(point[0],point[1],radius,Math.PI*angle_start,Math.PI*angle_end,false);
			context.lineTo(point[0],point[1]);
			context.fillStyle = colors[i];
			context.fill();
			context.beginPath();
			context.rect(legend_x,legend_y,rect_size,rect_size);
			context.fillStyle = colors[i];
			context.fill();
			context.beginPath();
			context.font = '12px sans-serif';
			context.fillText(values[i].toFixed(2)+'%',(legend_x + rect_size + (15*100/width) ),(legend_y + rect_size ));
			context.fillStyle = '#000000';
			context.fill();
			angle_start += percent[i];
			legend_y += rect_size + (40*100/width);
		}
	};
)}

It has a very simple usage, just save the code above in a file named graph.js and take a look:

<!DOCTYPE>
<html>
<head>
	<script type="text/javascript" src="graph.js">&lt;/script>
	<meta http-equiv="content-type" content="charset=utf-8" />
        <meta http-equiv="X-UA-Compatible" content="chrome=1" />
</head>
<body>
	<canvas id="pieChartId">If you are reading this please download http://code.google.com/intl/pt-BR/chrome/chromeframe/</canvas>
	<script type="text/javascript">graph('pieChartId',400,200,[100,200])</script>
</body>
</html>

The example above will generate charts with random colors, but if you prefer to use your color scheme, just pass an array with the same amount of itens passed in the values array, so we have something like:

graph('pieChartId',400,200,[100,200],['#ff0000','#000000']);
Posted by: thiagoribeiro | 2010/12/13

Converting your MySQL tables to mongodb collections

I needed to convert my mySQL database to mongodb collections. So I’ve written a PHP script to make this dirty work. It’s very simple to convert and if you need something like that, just copy the script below and run it. Pay attention if you have memory to get all entries in MySQL, if you don’t have just implement a new code to paginate the query to get these entries. Im my case I just used 500.000 entries and stopped here.

<?php
function getMyTables( $dbname ) {
 $tables = array();
 $sql = mysql_query("SHOW TABLES FROM $dbname ") or die("Error getting tables from $dbname");

 if( mysql_num_rows( $sql ) > 0 ) {
   while( $table = mysql_fetch_array( $sql ) ) {
     $explain = explainMyTable( $table[0] ); 
     $tables[$table[0]] = $explain;
    }
 }
 return $tables;
}

function explainMyTable( $tbname ) {
  $explain = array();
  $sql = mysql_query("EXPLAIN $tbname") or die("Error getting table structure");
  $i = 0;

  while( $get = mysql_fetch_array( $sql ) ) {
     array_push( $explain, $get[0] ); 
     $i++;
  }
  return $explain;
}

function checkEncode($string) {
  if( !mb_check_encoding($string,'UTF-8')) {
    return mb_convert_encoding($string,'UTF-8','ISO-8859-1');
  } else {
    return $string;
  }
}

$mydb   = "YOUR_MYSQL_DB_NAME";
$myconn = mysql_connect('MYSQL_HOST','MYSQL_USER','MYSQL_PASS');
$setmydb   = mysql_select_db( $mydb );
$mytables = getMyTables( $mydb );

$modb   = "YOUR_MONGO_DB_NAME";

try {
  $moconn = new Mongo();
  $modb = $moconn->selectDB( $modb );
} catch(MongoConnectionException $e) {
  die("Problem during mongodb initialization. Please start mongodb server.");
}

foreach( $mytables as $table => $struct ) {
  $sql = mysql_query("SELECT * FROM $table LIMIT 0 , 500000") or die( mysql_error() );
  $count = mysql_num_rows( $sql );

  // Starts new collection on mongodb
  $collection = $modb->$table;

  // If it has content insert all content
  if( $count > 0 ) {
    while( $info = mysql_fetch_array( $sql, MYSQL_NUM )) {
      $infosize = count( $info );
      $mosql = array();

      for( $i=0; $i < $infosize; $i++ ) {
        $mosql[$struct[$i]] = checkEncode($info[$i]);
  }

  $collection->insert($mosql);
  }
// Only create a new entry empty
} else {
  for( $i=0; $i < $infosize; $i++ ) {
    $mosql[$struct[$i]] = '';
  }

  $collection->insert($mosql);
  }
}

echo "Done! Please, check your mongodb collection and have fun!";
?>
Posted by: thiagoribeiro | 2010/06/29

Fixing Latin1 problem with accentuation on typeface

I’ve been using typeface to render my websites fonts. It’s a good tool, but some characters were broken during typeface render on latin1 encoding.  At the typeface website doesn’t have some recommendations to insert the correct charset inside <script> tag. So it’s easy to fix the problem, look that:

<script charset=”utf-8″ src=”your_typeface_font.js”></script>

Posted by: thiagoribeiro | 2010/05/22

Fixing HP iLO jvm problem to open remote console

I’ve installed Sun Java JDK in my Debian, and linked jdk/jre/lib/amd64/libnpjp2.so lib to google chrome plugins dir. So I needed to connect into remote console of HP iLo.

While jvm was loading the remote console, an error was ocurred and the initial loading was stopped. To fix this problem is really simple and we have two ways:

First Option

Disable ipv6 bind at /etc/sysctl.d/bindv6only.conf. To disable this property just change the value 1 to 0 and  after that run the command below as root user:

# sysctl -p /etc/sysclt.d/bindv6only.conf

Restart your navigator.

Second Option

You can disable jvm ipv6 reading directly into the file ~/.java/deployment/deploymennt.properties. Just open the file and add this setting:

deployment.javaws.jre.0.args=-Djava.net.preferIPv4Stack\=true

And now, that’s ok. You’re done to use your HP iLo without troubles. Good luck.

Posted by: thiagoribeiro | 2009/11/26

Creating and converting icons to gnome dia – Part I

Before I start, I’d like to say thanks to all people that are using the icons that I made. I confess that I’m surprised with a lot of mails that I’ve been receiving about this project.

I know that there are a lot of guys curious about to convert their icons to shape file format.  So, finally I’m trying to dedicate a time to explain how to do that.

The first thing that we need to think is that shape files are totally limited. During my work to convert these icons I’ve noticed some details about its creation:

  • Do not try to use gradient in shape files. If you need this effect you must construct this using retangular objects in a color scale.
  • The format entitled plain svg by Inskscape has some differences if comparing to shape, an important difference is that colors are referenced by names in svg and referenced by hexadecimal in shape.
  • Depending of the way that the object was made, probably you’ll need to remake this. Some resources used in vetorial applications doesn’t work to shape format.
  • Try not to use lines when you’re drawing an object to be saved in a shape file. Sometimes, I don’t know what happens that the line looses its coordinates. So, use a thin rectangle filled in the color that you want.
  • Do not use outlined objects. If you need an object outlined, you must use two objects in a different size and pick up the lower on the largest. Your largest object is your outline.

To be continued.

Posted by: thiagoribeiro | 2009/03/24

New databases icons available for Dia

During the conference “Boteco 4Linux – Pentaho” I saw a network map using the icons that I’ve published. So I noticed that they needed specific network icons to represents databases  servers. They was using a default database icon with the PostgreSQL logo as example. When I arrived home I decided to make these icons to improve the project. Now we have four more icons on the project:

  • IBM DB2 Database Server;
  • PostgreSQL Database Server;
  • Oracle Database Server; and
  • mySQL Database Server.

I asked some friends to submit me a list of icons that can be usefull and necessary in a network scheme, and you’re invited to do the same posting your list here. Next I’ll see the most relevant icons and published them. Take a look at the screenshot below:

New database icons

Please, visit the project page to make the download.

Posted by: thiagoribeiro | 2008/08/18

New network icons schema to Gnome Dia

After a lot of time searching some friendly icons to be used in Dia and no results obtained, I decided to face this problem and generate my own icons collection.

I like Gnome Gorilla’s icons style very much, so I decided to convert most of them to Dia. I had to mix some icons to make a new in according its preposition.

I found out on Net the svg2shape.xslt to make the conversion, but many erros came up when I tried to convert an Inkscape plain SVG.

Problems associated with compability was seen. An example about is that a shape file doesn’t accept opacity. Many Gnome icons have opacity and they are constructed using a different structure to be in conformity with Dia. Another problem detected is that shape files don’t accept colors by their names. You can’t use black to describe a black color, only hexadecimals six digits are accepted.

I’ve written a PHP script to read the shape file created by the command xsltproc and make some modifications to correct them. In a future post I can explain better this and post the hard way to get this.

Here you can see a simple result of the conversion and adaptation:

Gnome icons scheme to Dia

Gnome icons schema to Dia

If you liked it, click here to make the icons download. To add this in your Dia you just need to follow the next step:

# cd /usr/share/dia

# cp PATH/rib-network.tar.gz .

# tar zxvf rib-network.tar.gz

If your Dia is started please close this and start it again. So in your combo list choice RIB-Network. Now you can be free to create your Network diagrams with a lot of colors and beauty. :)

Older Posts »

Categories

Follow

Get every new post delivered to your Inbox.