Twitter

Google Charts zoom in dataset example

google-chartsI took me a while to understand how Google Charts can be extended with a zoom/drill in data set feature. You have to add then google.visualization.events.addListener method which fetch the selected datapoint of a graph. With some extra javascript code you can reload the chart with a more detailed dataset. See example below!

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["bar"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {

      var options = {
          bars: "vertical",
          bar: {groupWidth: "90%"},
          legend: { position: "none"},
          vAxis: {format: "decimal"},
          isStacked:true,colors: ["#0066cc", "#808080"],vAxis: { format:"decimal", viewWindow: { min: 0, max: ".round($max_forecast+100)." } }, series: {
            3: {
                targetAxisIndex: 1
            }
          }
        };

        var data = google.visualization.arrayToDataTable([['','Low (kWh)','Normal (kWh)','Solar (kWh)','Forecast (kWh)'],['2006',0,0,0,0],['2007',0,0,0,0],['2008',0,0,0,0],['2009',0,0,0,0],['2010',0,0,0,0],['2011',0,0,0,0],['2012',0,0,0,0],['2013',0,0,0,0],['2014',0,0,0,0],['2015',0,0,0,0],['2016',20,20,11,278.75]]);
        var chart = new google.charts.Bar(document.getElementById("chart_div"));
        chart.draw(data, google.charts.Bar.convertOptions(options));

        google.visualization.events.addListener(chart, "select", selectHandler);

        function selectHandler(e)     {
           var year = data.getValue(chart.getSelection()[0].row, 0);
           link("pid=30&eid=88&date="+year+"-1-1");
        }
      }
function link(value)
{
	var form = document.forms['plaatenergy'];
	var newInput = document.createElement('input');
	newInput.setAttribute('type','hidden');
	newInput.setAttribute('name','token');
	newInput.setAttribute('value',value);
	form.appendChild(newInput);		
		
	form.submit();
}

VPS 512MB config

Yesterday i upgraded my VPS from 256MB to 512MB memory (1GB Burst) to have some more resources to handle traffic.

On this VPS the following software is installed:
– Ubuntu 10
– Apache 2.2.16
– MySQL 5.1.61
– PHP 5.5.3

I am running five website with regular traffice (+/- 15.000 requests a day) on the VPS:
– PlaatScrum (Self made PHP site)
– PlaatSoft (WordPress site)
– Family van der Plaat (WordPress site)
– Education (Self made PHP site)
– Service (Self made PHP site)

I found out the below configuration results in the best performance:

Apache2

The following modules are activated:
– alias
– dir
– mime
– negotiation
– php5
– rewrite
– status

The following apache2.conf is active:

MaxKeepAliveRequests 0
KeepAliveRequests 15

[mpm_prefork_module]
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxClients 30
MaxRequestsPerChild 0

[mpm_worker_module]
StartServers 1
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxClients 30
MaxRequestsPerChild 0

[mpm_event_module]
StartServers 1
MaxClients 30
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestsPerChild 0

MySQL

[mysqld]
skip-innodb

key_buffer = 8M
max_allowed_packet = 16M
thread_stack = 192K
thread_cache_size = 4

myisam-recover = BACKUP
max_connections = 50
table_cache = 128

query_cache_limit = 512K
query_cache_size = 8M

VPS 256MB config

I am using for two weeks a VPS with 256MB memory. On this VPS the following software is installed:
– Ubuntu 10
– Apache 2.2.16
– MySQL 5.1.61
– PHP 5.5.3

I am running five website with regular traffice (+/- 15.000 requests a day) on the VPS:
– PlaatScrum (Self made PHP site)
– PlaatSoft (WordPress site)
– Family van der Plaat (WordPress site)
– Education (Self made PHP site)
– Service (Self made PHP site)

I found out the below configuration results in the best performance:

Apache2

[mpm_prefork_module]
StartServers 1
MinSpareServers 2
MaxSpareServers 2
MaxClients 15
MaxRequestsPerChild 0

[mpm_worker_module]
StartServers 1
MinSpareThreads 2
MaxSpareThreads 2
ThreadLimit 64
ThreadsPerChild 25
MaxClients 15
MaxRequestsPerChild 0

[mpm_event_module]
StartServers 1
MaxClients 15
MinSpareThreads 2
MaxSpareThreads 2
ThreadLimit 64
ThreadsPerChild 25
MaxRequestsPerChild 0

MySQL

[mysqld]
skip-innodb

key_buffer = 8M
max_allowed_packet = 16M
thread_stack = 192K
thread_cache_size = 4

myisam-recover = BACKUP
max_connections = 50
table_cache = 128

query_cache_limit = 512K
query_cache_size = 8M

WAMP + PostgreSQL integration

If you want to extend an existing Windows WAMP installation with a PostgreSQL database execute the following steps:

Apache 2.2.X configuration
Add the next line to the Apache 2.2.x httpd.conf configuration:
LoadFile “C:/Program Files/PostgreSQL/9.1/bin/libpq.dll”

Above line must be entered before the next line.
LoadModule php5_module “c:/wamp/bin/php/php5.2.11/php5apache2_2.dll”

PHP 5.2.X Configuration
Enable (remove trailing ; character) the following two lines in the php.ini configuration file.
extension=php_pdo_pgsql.dll
extension=php_pgsql.dll

Restart WAMP
Restart the wamp (apache, php and mysql) software.

Test
Create the following test.php file and place it in the apache www root directory:

<?php
echo extension_loaded('pgsql') ? 'yes':'no';
?>

When the php file is executed (http://127.0.0.1/test.php) in apache the following information must be showed on screen.

yes

PHP stock information example

Hereby an easy example how you can use the finance.yahoo.com webservice to fetch stock exchange information with PHP.


	function warquest_stockarray($data,$delim=',',$enclosure='"') {
		$enclosed=false;
		$fldcount=0;
		$linecount=0;
		$fldval='';
		for($i=0;$i<strlen($data);$i++) {
			$chr=$data{$i};
			switch($chr)
			{
				case $enclosure:
					if($enclosed&&$data{$i+1}==$enclosure) {
						$fldval.=$chr;
						++$i; 
					} else {
						$enclosed=!$enclosed;
					}
					break;
   
				case $delim:
					if(!$enclosed) {
						$ret_array[$linecount][$fldcount++]=$fldval;
						$fldval='';
					} else {
						$fldval.=$chr;
					}
					break;
				
				case "\r":
					if (!$enclosed&&$data{$i+1}=="\n") continue;
					
				case "\n":
					if(!$enclosed) {
						$ret_array[$linecount++][$fldcount]=$fldval;
						$fldcount=0;
						$fldval='';
					} else {
						$fldval.=$chr;
					}
					break;
				
				default:
					$fldval.=$chr;
			}
		}
		if($fldval) {
			$ret_array[$linecount][$fldcount]=$fldval;
		}
		return $ret_array;
	}

	function warquest_stock($stocksymbols) {		
		$url = sprintf("http://download.finance.yahoo.com/d/quotes.csv?s=%s&f=snl1d1t1c1ohgvp", $stocksymbols);
		$data = file_get_contents($url);
	
		$stocklist=warquest_stockarray($data);
	
		for($i=0;$i<count($stocklist);$i++) {
		
			$stocksymbol=trim($stocklist[$i][0], '\"');
			$stock[$stocksymbol]["stocksymbol"] = 
			$stock[$stocksymbol]["company"] = trim($stocklist[$i][1], '\"');
			$stock[$stocksymbol]["last"] = $stocklist[$i][2];
			$stock[$stocksymbol]["date"] = trim($stocklist[$i][3], '\"');	
			$stock[$stocksymbol]["time"] = trim($stocklist[$i][4], '\"');					
			$stock[$stocksymbol]["change"] = $stocklist[$i][5];
			$stock[$stocksymbol]["open"] = $stocklist[$i][6];
			$stock[$stocksymbol]["high"] = $stocklist[$i][7];
			$stock[$stocksymbol]["low"] = $stocklist[$i][8];
			$stock[$stocksymbol]["volume"] = $stocklist[$i][9];
			$stock[$stocksymbol]["prevclose"] = $stocklist[$i][10];	
		}
		return $stock;
	}
	
	print_r(warquest_stock("DB"));


Drupal 5.x to 6.x migration

Last night I migrated the oostpoort website from Drupal 5.x to Drupal 6.x. The following steps did i executed to successful migrate the website.

1. Downloaded for each used 5.x module the 6.x release.
2. Make first backup.
3. Upgrade Drupal 5.20 to latest available level 5.22.
4. Upgrade all used Drupal 5.x modules to latest available level.
5. Make second backup.
6. Disable all none core related modules
7. Uninstall update_status 5.x module
8. Remove all Drupal 5.x modules from file system
9. Remove Drupal 5.x core files from file system.
10. Install Drupal 6.x core on file system
11. Configure settings.php (Take the new 6.x template as base) with correct database settings. Set $update_free_access to TRUE.
12. Access the website.
13. Run update.php two times
14. Now the system runs without any issues on Drupal 6.x
15. Install all needed Drupal 6.x modules.
16. Enable all modules and run again update.php
17. Change $update_free_access to FALSE in settings.php
18. Optional: Update theme template
19. Optional: Make third backup.

Some remarks:
– All these steps took four hours in total.
– If in the drupal configuration the start URL is “frontpage” replace it which “node” else the frontpage is not working anymore.
– If any of these steps fail restore the website which the available backup.

Inno Setup review

Yesterday I did some tests with the Inno Setup. This freeware product is really great. Within 30 minutes I have complety customized a Windows Setup Installer for my PlaatStats tool. So if you are searching for a easy to use Windows Setup Installer checkout the following link

QtCreator 1.3.81 not stable

Hi everybody, Some days ago i have upgraded QtCreator (Windows release) from 1.3.1 to 1.3.81 (2.0.0 alpha). This release is not stable with a SubVersion Qt project. Problem is that with or without a Windows subversion client installed (Tigris.org SubVersion client v1.5.8) QtCreator is crashing during the indexing of the Qt SVN project. When I remove all .svn directories out of my Qt project QtCreator is running fine. So what could be wrong? Looking forward to a fix for this critical issue?

My bug report send to the Qt

P.S. With QtCreator 1.3.1 with trigris.org SubVersion plugin is working fine!

JasperReports basic example

Hi everybody,

Today i have played around with JasperReports. Really nice java tool to created very easy reports. I did not find many examples on internet. Therefor I post my first try. I hope this will help other developers starting up with this great tool.

This example runs a query (JDBC connected) with some parameters define in Java. The result is converted to PDF and then zipped.

Test.java file


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import java.sql.Connection;
import java.sql.DriverManager;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;

/**
 * The Class Test.
 */
public class Test {

	/** The Constant LOG. */
	private static final Logger LOG = Logger.getLogger(test.class);
	
	/** The Constant BUFFER. */
	final static int BUFFER = 10240;
	
	/** The connection. */
	static Connection connection = null;

	/**
	 * Connect database.
	 */
	static void ConnectDatabase() {
		try {			
			// Load the JDBC driver
			String driverName = "oracle.jdbc.driver.OracleDriver";
			Class.forName(driverName);

			// Create a connection to the database
			String serverName = "127.0.0.1";
			String portNumber = "1521";
			String sid = "XE";
			String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid;
			String username = "test";
			String password = "test";
			connection = DriverManager.getConnection(url, username, password);
		} catch (ClassNotFoundException e) {
			System.err.println("Could not find the database driver");
		} catch (Exception e) {
			System.err.println("Could not connect to the database");
		}
	}

	/**
	 * File zip.
	 */
	static void fileZip() {
		
		BufferedInputStream origin = null;
		try
		{
			FileOutputStream dest = new FileOutputStream("test.zip");
			ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
			byte data[] = new byte[BUFFER];
			
			// get a list of files from current directory
			File f = new File("src/.");
			String files[] = f.list();

			for (int i=0; i<files.length; i++) {
			
				System.out.println("Adding: "+files[i]);
				FileInputStream fi = new FileInputStream("src/"+files[i]);
				origin = new BufferedInputStream(fi, BUFFER);
				ZipEntry entry = new ZipEntry(files[i]);
				out.putNextEntry(entry);
				int count;
				while((count = origin.read(data, 0, BUFFER)) != -1) {
					out.write(data, 0, count);
				}
				origin.close();
			}
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
     
	/**
	 * The main method.
	 * 
	 * @param args the arguments
	 */
	public static void main(String[] args) {
		JasperReport jasperReport;
		JasperPrint jasperPrint;
		
		long start = System.currentTimeMillis();
		
		try {			
			// Log log4j configuration
			final Properties log4jProperties = new Properties();
			log4jProperties.load(new FileInputStream("etc/log4j.properties"));
			PropertyConfigurator.configure(log4jProperties);
			
			LOG.info("Start");
			LOG.info("--------");
						
			LOG.info("Compile Jasper XML Report");
			jasperReport = JasperCompileManager.compileReport("src/test.jrxml");
			LOG.info("time : " + (System.currentTimeMillis() - start)+ " ms.");
			
			LOG.info("Create Database connection");
			ConnectDatabase();
			LOG.info("time : " + (System.currentTimeMillis() - start)+ " ms.");
			
			LOG.info("Create parameters");
			Map <String, Object> parameters = new HashMap<String, Object>();
			parameters.put("ReportTitle", "User Report");
			parameters.put("DataFile", "src/test1.jrxml");
			parameters.put("IdRange", 10);	
			
			LOG.info("Generated report");
			jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, connection);
			LOG.info("time : " + (System.currentTimeMillis() - start)+ " ms.");
			
			LOG.info("Generated PDF");
			JasperExportManager.exportReportToPdfFile(jasperPrint, "src/test.pdf");
			LOG.info("time : " + (System.currentTimeMillis() - start)+ " ms.");
			
			LOG.info("Create Zip File");
			fileZip();
			LOG.info("time : " + (System.currentTimeMillis() - start)+ " ms.");
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		LOG.info("--------");
		LOG.info("Done");
	}
}

JaspersReports test.jrxml (Report template) file.

<?xml version="1.0"?>

<jasperReport
		xmlns="http://jasperreports.sourceforge.net/jasperreports"
		xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
		name="User Overview" pageWidth="595" pageHeight="842" columnWidth="515" leftMargin="40" rightMargin="40" topMargin="50" bottomMargin="50">


	<style name="Sans_Bold" isDefault="false" fontName="DejaVu Sans" fontSize="8" isBold="true" isItalic="false" isUnderline="false" isStrikeThrough="false"/>
	<style name="Sans_Normal" isDefault="true" fontName="DejaVu Sans" fontSize="8" isBold="false" isItalic="false" isUnderline="false" isStrikeThrough="false"/>
	<style name="Title" style="Sans_Bold" fontSize="12"/>
	<style name="ColumnHeader" style="Sans_Bold" forecolor="white"/>
	
	<parameter name="ReportTitle" class="java.lang.String"></parameter>
	<parameter name="DataFile" class="java.lang.String"></parameter>
	<parameter name="IdRange" class="java.lang.Integer"></parameter>
	
	<queryString><![CDATA[SELECT id, displaynaam, puik_id FROM gebruiker WHERE id <=$P{IdRange} order by id]]></queryString>
	<field name="id" class="java.lang.Integer"/>
	<field name="displaynaam" class="java.lang.String"/>
	<field name="puik_id" class="java.lang.String"/>
	
	<title>
		<band height="70">
			<line>
				<reportElement x="0" y="0" width="515" height="1"/>
				<graphicElement/>
			</line>
			<textField isBlankWhenNull="true" bookmarkLevel="1">
				<reportElement x="0" y="10" width="515" height="30" style="Sans_Normal"/>
				<textElement textAlignment="Center">
					<font size="22"/>
				</textElement>
				<textFieldExpression class="java.lang.String"><![CDATA[$P{ReportTitle}]]></textFieldExpression>
				<anchorNameExpression><![CDATA["Title"]]></anchorNameExpression>
			</textField>
			<textField isBlankWhenNull="true">
				<reportElement x="0" y="40" width="515" height="20" style="Sans_Normal"/>
				<textElement textAlignment="Center">
					<font size="14"/>
				</textElement>
				<textFieldExpression class="java.lang.String"><![CDATA[$P{DataFile}]]></textFieldExpression>
			</textField>
		</band>

	</title>
	
	<pageHeader>
		<band height="15">
			<frame>
				<reportElement x="0" y="0" width="555" height="15" mode="Opaque" backcolor="black"/>
				<staticText>
					<reportElement x="5" y="0" width="155" height="15" style="ColumnHeader"/>
					<textElement verticalAlignment="Middle" textAlignment="Left"/>
					<text>Id</text>
				</staticText>
				<staticText>
					<reportElement x="125" y="0" width="100" height="15" style="ColumnHeader"/>
					<textElement verticalAlignment="Middle"/>
					<text>Displaynaam</text>
				</staticText>
				<staticText>
					<reportElement x="270" y="0" width="60" height="15" style="ColumnHeader"/>
					<textElement verticalAlignment="Middle" textAlignment="Left"/>
					<text>PuikId</text>
				</staticText>
				</frame>
		</band>
	</pageHeader>
							
 <detail>
 	<band height="15">
			<frame>
				<reportElement x="0" y="0" width="555" height="15" />
				<textField>
					<reportElement x="5" y="0" width="155" height="15"/>
					<textElement verticalAlignment="Middle" textAlignment="Left"/>
					<textFieldExpression>$F{id}.toString()</textFieldExpression>
				</textField>
				<textField>
					<reportElement x="125" y="0" width="100" height="15"/>
					<textElement verticalAlignment="Middle"/>
					<textFieldExpression>$F{displaynaam}</textFieldExpression>
				</textField>
				<textField pattern="#,###.00">
					<reportElement x="270" y="0" width="60" height="15"/>
					<textElement verticalAlignment="Middle" textAlignment="Left"/>
					<textFieldExpression>$F{puik_id}</textFieldExpression>
				</textField>
			</frame>			
		</band>	
  </detail>
  
  <pageFooter>
		<band height="40">
			<line>
				<reportElement x="0" y="10" width="515" height="1"/>
				<graphicElement/>
			</line>
			<textField>
				<reportElement x="200" y="20" width="80" height="15"/>
				<textElement textAlignment="Right"/>
				<textFieldExpression class="java.lang.String"><![CDATA["Page " + String.valueOf($V{PAGE_NUMBER}) + " of"]]></textFieldExpression>
			</textField>
			<textField evaluationTime="Report">
				<reportElement x="280" y="20" width="75" height="15"/>
				<textElement/>
				<textFieldExpression class="java.lang.String"><![CDATA[" " + String.valueOf($V{PAGE_NUMBER})]]></textFieldExpression>
			</textField>			
		</band>
	</pageFooter>
  	
	<lastPageFooter>
		<band height="60">
			<textField bookmarkLevel="1">
				<reportElement x="0" y="10" width="515" height="15"/>
				<textElement textAlignment="Center"/>
				<textFieldExpression class="java.lang.String"><![CDATA["There were " + 
					String.valueOf($V{REPORT_COUNT}) + 
					" address records on this report."]]></textFieldExpression>
				<anchorNameExpression><![CDATA["Summary"]]></anchorNameExpression>
			</textField>
			<line>
				<reportElement x="0" y="30" width="515" height="1"/>
				<graphicElement/>
			</line>
			<textField>
				<reportElement x="200" y="40" width="80" height="15"/>
				<textElement textAlignment="Right"/>
				<textFieldExpression class="java.lang.String"><![CDATA["Page " + String.valueOf($V{PAGE_NUMBER}) + " of"]]></textFieldExpression>
			</textField>
			<textField evaluationTime="Report">
				<reportElement x="280" y="40" width="75" height="15"/>
				<textElement/>
				<textFieldExpression class="java.lang.String"><![CDATA[" " + String.valueOf($V{PAGE_NUMBER})]]></textFieldExpression>
			</textField>
		</band>
	</lastPageFooter>
		
</jasperReport>

Log4j.properties file

log4j.rootLogger=INFO, console, logfile
log4j.appender.logfile.File=../log/test.log

# Appender to log4j.log
log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.MaxFileSize=1000KB
log4j.appender.logfile.MaxBackupIndex=9
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d{dd-MM-yyyy HH:mm:ss,SSS} %-5p (%c:%L) - %M: %m%n
log4j.appender.logfile.Append=true

# Appender to Console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{dd-MM-yyyy HH:mm:ss,SSS} %-5p (%c:%L) - %M: %m%n

GRRLIB 4.2.X Freetype support

In this post i have add information how to add freetype library support to the GRRLIB 4.2.X library

GRRLIB_free_print.h

void GRRLIB_InitFreetype();

void GRRLIB_initTexture(void);

void GRRLIB_Printf2(	int x, 
							int y, 
							const char *string, 
							unsigned int fontSize, 
							int color); 

GRRLIB_texImg* GRRLIB_GetTexture(void);

GRRLIB_free_print.c

#include <malloc.h>
#include <stdarg.h>
#include <stdio.h>

#include <grrlib.h>

#include <ft2build.h> /* I presume you have freetype for the Wii installed */
#include FT_FREETYPE_H

#include "font_ttf.h"

static FT_Library ftLibrary;
static FT_Face ftFace;

void *fontTempLayer=NULL;
void *fontTexture=NULL;
GRRLIB_texImg image;

extern  Mtx                  GXmodelView2D;

/* Static function prototypes */
static void BitmapTo4x4RGBA(const unsigned char *src, void *dst, const unsigned int width, const unsigned int height);
static bool BlitGlyph(FT_Bitmap *bitmap, int offset, int top, int color) ;

void GRRLIB_InitFreetype(void) 
{
	unsigned int error = FT_Init_FreeType(&ftLibrary);
	if (error) 
	{
		exit(0);
	}

	error = FT_New_Memory_Face(ftLibrary, font_ttf, font_ttf_size, 0, &ftFace);
	if (error == FT_Err_Unknown_File_Format) 
	{
		exit(0);
	} 
	else if (error) 
	{
		/* Some other error */
		exit(0);
	}
}

void GRRLIB_initTexture(void)
{
   // Clear previous video frame buffer
   if (fontTexture!=NULL) free(fontTexture);

   fontTempLayer = (void*) calloc(1, 640 * 528 * 4);

   if (fontTempLayer == NULL) 
   {
	  /* Oops! Something went wrong! */
	  exit(0);
   }
}

void GRRLIB_Printf2(int x, int y, const char *string, unsigned int fontSize, int color) 
{
	unsigned int error = 0;
	int penX = 0;
	int penY = fontSize;
	FT_GlyphSlot slot = ftFace->glyph;
	FT_UInt glyphIndex = 0;
	FT_UInt previousGlyph = 0;
	FT_Bool hasKerning = FT_HAS_KERNING(ftFace);

    error = FT_Set_Pixel_Sizes(ftFace, 0, fontSize);
	if (error) 
	{
		/* Failed to set the font size to the requested size. 
		 * You probably should set a default size or something. 
		 * I'll leave that up to the reader. */
		 FT_Set_Pixel_Sizes(ftFace, 0, 12);
	}
	
	/* Convert the string to UTF32 */
	size_t length = strlen(string);
	wchar_t *utf32 = (wchar_t*)malloc(length * sizeof(wchar_t)); 
	length = mbstowcs(utf32, string, length);
	
	/* Loop over each character, drawing it on to the 4, until the 
	 * end of the string is reached, or until the pixel width is too wide */
	unsigned int loop = 0;
	for (loop = 0; loop < length; ++loop)
    {
		glyphIndex = FT_Get_Char_Index(ftFace, utf32[ loop ]);
		
		/* To the best of my knowledge, none of the other freetype 
		 * implementations use kerning, so my method ends up looking
		 * slightly better 🙂 */
		if (hasKerning && previousGlyph && glyphIndex) 
		{
			FT_Vector delta;
			FT_Get_Kerning(ftFace, previousGlyph, glyphIndex, FT_KERNING_DEFAULT, &delta);
			penX += delta.x >> 6;
		}
	
		error = FT_Load_Glyph(ftFace, glyphIndex, FT_LOAD_RENDER);
		if (error)
        {
			/* Whoops, something went wrong trying to load the glyph 
			 * for this character... you should handle this better */
			continue;
		}
	
		if (BlitGlyph(&slot->bitmap, penX + slot->bitmap_left+x, penY - slot->bitmap_top+y, color) == true) 
		{
			/* The glyph was successfully blitted to the buffer, move the pen forwards */
			penX += slot->advance.x >> 6;
			previousGlyph = glyphIndex;
		} 
		else 
		{
			/* BlitGlyph returned false, the line must be full */
			free(utf32);
			return;
		}
	}

	free(utf32);
}

/* Returns true if the character was draw on to the buffer, false if otherwise */
bool BlitGlyph(FT_Bitmap *bitmap, int offset, int top, int color) 
{
	int bitmapWidth = bitmap->width;
	int bitmapHeight = bitmap->rows;

	if (offset + bitmapWidth > 640) 
	{
		/* Drawing this character would over run the buffer, so don't draw it */
		return false;
	}

	/* Draw the glyph onto the buffer, blitting from the bottom up */
	/* CREDIT: Derived from a function by DragonMinded */
	unsigned char *p = fontTempLayer;
	unsigned int y = 0;
	for (y = 0; y < bitmapHeight; ++y) 
	{
		int sywidth = y * bitmapWidth;
		int dywidth = (y + top) * 640;

		unsigned int column = 0;
		for (column = 0; column < bitmapWidth; ++column)
        {
			unsigned int srcloc = column + sywidth;
			unsigned int dstloc = ((column + offset) + dywidth) << 2;
			
			/* Copy the alpha value for this pixel into the texture buffer */
			p[ dstloc + 0 ] = (color & 0xff);
			p[ dstloc + 1 ] = ((color >> 8) & 0xff);
			p[ dstloc + 2 ] = ((color >> 16) & 0xff);
			p[ dstloc + 3 ] = (bitmap->buffer[ srcloc ]);
		}
	}
	
	return true;
}

/* Render the text string to a 4x4RGBA texture, return a pointer to this texture */
GRRLIB_texImg* GRRLIB_GetTexture(void) 
{
	/* Create a new buffer, this time to hold the final texture 
	 * in a format suitable for the Wii */
	fontTexture = memalign(32, 640 * 528 * 4);

	/* Convert the RGBA temp buffer to a format usuable by GX */
	BitmapTo4x4RGBA(fontTempLayer, fontTexture, 640, 528);
	DCFlushRange(fontTexture, 640 * 528 * 4);

	/* The temp buffer is no longer required */
	free(fontTempLayer);
	image.data=fontTexture;
	image.w=640;
	image.h=528;
	
	return &image;
}

void BitmapTo4x4RGBA(const unsigned char *src, void *dst, const unsigned int width, const unsigned int height)
{
	unsigned int block = 0;
	unsigned int i = 0;
	unsigned int c = 0;
	unsigned int ar = 0;
	unsigned int gb = 0;
	unsigned char *p = (unsigned char*)dst;

	for (block = 0; block < height; block += 4) {
		for (i = 0; i < width; i += 4) {
			/* Alpha and Red */
			for (c = 0; c < 4; ++c) {
				for (ar = 0; ar < 4; ++ar) {
					/* Alpha pixels */
					*p++ = src[(((i + ar) + ((block + c) * width)) * 4) + 3];
					/* Red pixels */	
					*p++ = src[((i + ar) + ((block + c) * width)) * 4];
				}
			}
			
			/* Green and Blue */
			for (c = 0; c < 4; ++c) {
				for (gb = 0; gb < 4; ++gb) {
					/* Green pixels */
					*p++ = src[(((i + gb) + ((block + c) * width)) * 4) + 1];
					/* Blue pixels */
					*p++ = src[(((i + gb) + ((block + c) * width)) * 4) + 2];
				}
			}
		} /* i */
	} /* block */
}

Wii trace module

To debug better a Wii application / game i have created a trace C++ module with is logging trace event to file. Please checkout the following code. I hope it benefit someone!

trace.h

#ifndef TRACE_H
#define TRACE_H

class Trace
{
  private:
	FILE * fp;
	char * getDate();

  public:
  	// Constructor & Destructor
	Trace();
 	~Trace();
	
	// Methodes
	int open(const char *filename);
	int event( const char *functionName, int threadNr, const char *event, ...);
	int eventRaw( char character);
	int close();
};

#endif

trace.cpp

#include <stdio.h>
#include <gccore.h>
#include <ogcsys.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <ogcsys.h>
#include <stdarg.h>
#include <time.h>

#include "trace.h"

// Enable / Disable trace file functionality
bool traceOn = false;

// ------------------------------
// Constructor
// ------------------------------

Trace::Trace()
{
	fp=NULL;
}

// ------------------------------
// Destructor
// ------------------------------

Trace::~Trace()
{
  close();
}

// ------------------------------
// Methods
// ------------------------------

// Open trace file
int Trace::open(const char *filename)
{
   int returnValue=0;
   
   if (!traceOn) return -1;
         
   if((fp=fopen(filename, "wb"))==NULL) 
   {
      printf("Error: Cannot open trace file.\n");
      returnValue=-2;
   }   
   return returnValue;
}


// Close trace file
int Trace::close()
{
   int returnValue=0;
   
   if (fp!=NULL)
   {
       fclose(fp);
   }	
   return returnValue;
}


// Create trace timestamp
char * Trace::getDate()
{
  struct tm *now = NULL;
  time_t time_value = 0;
  static char buf[ 128 ] ;
  
  // Clear memory  
  memset(buf, sizeof(buf), 0x00);
  
  /* Get time value */
  time_value = time(NULL);          
  
  /* Get time and date structure */
  now = localtime(&time_value);     

  // Create time stamp
  sprintf(buf,"%02d-%02d-%04d %02d:%02d:%02d",
	now->tm_mday, now->tm_mon+1, now->tm_year+1900, 
	now->tm_hour,now->tm_min,now->tm_sec);
	
  return buf;
}

// Save trace event in trace file
int Trace::event( const char *functionName, int threadNr, const char *event, ...)
{
   int returnValue=0;
   char buf[ MAX_LEN ];
   
   // Clear memory  
   memset(buf, MAX_LEN, 0x00);
   
   if (!traceOn) return -1;
   
   // Expend event string
   va_list list;
   va_start(list, event );
   vsprintf(buf, event, list);
   
   if (fp!=NULL)
   {
      // Save string to file
	  fprintf(fp,"%s [thread%d-%s] %s\n",getDate(), threadNr, functionName, buf); 
	  fflush(fp); 
   }
   
   return returnValue;
}


// Save trace event in trace file
int Trace::eventRaw( char character)
{
   int returnValue=0;
   
   if (!traceOn) return -1;
     
   if (fp!=NULL)
   {
      // Save string to file
	  fprintf(fp,"%c",character); 
	  fflush(fp); 
   }
   
   return returnValue;
}

Freeware LDAP server for Windows

For a project i needed a Windows LDAP server (client) software. I try out some commercial and freeware tools. Add the end i like Apache Directory Server the most. So if you are searching for a freeware easy to use LDAP solution for Windows checkout this product.

Apache Directory Server
ApacheDS is an embeddable directory server entirely written in Java, which has been certified LDAPv3 compatible by the Open Group. Besides LDAP it supports Kerberos 5 and the Change Password Protocol. It has been designed to introduce triggers, stored procedures, queues and views to the world of LDAP which has lacked these rich constructs.

Apache Directory Studio
The Studio is an LDAP client platform. It is composed of an Eclipse RCP Application and a set of plugins. Primarily it is built to be used with ApacheDS, but it should work with any LDAP server.

Missing Administration tools in Windows XP

Problem:
If you miss the “Administration tools” menu in Windows XP. How can i access these tools without this menu?

Solution:
All the tools in the Administrative tools folder point to Management Console files. Do a search on your Windows system for c:\windows\system32\*.msc and you’ll find them. The make a shortcut on the desktop to access them!

Tip: Windows disk manager tool can be start by entering “compmgmt.msc” in the “Run” section!

Eclipse: editor does not contain a main type java

Problem:
Eclipse give “editor does not contain a main type” error when you start a class with contain a valid main method.

I know if I enable Maven dependency, that Eclipse will not be able to find the main method. Is it possible to take a class out of the classpath (java.build.path) if it is in the default directory?

Solution:
I had the same problem, I have to add that file to build path. after adding that file to build path. It worked fine. Go to package explorer –> build –> Add to build path || Include. This will solve the issue

Could not open `C:\Program Files\Java\jdk1.6.0_05\lib\i386\jvm.cfg’

Problem:
I am geting this error when I enter the “java” command: “Error: could not open `C:\Program Files\Java\jdk1.6.0_05\lib\i386\jvm.cfg'”

I have configured the PATH variable (Windows XP) and “javac” works. I cannot, however, get my programs to run because of the error every time I type “java”. Also, I did not install my JDK / SDK to the directory in which the computer is looking for the “java” cammand (ie. it is not in ‘Program Files’…). If anyone can help, it would be greatly appreciated. Thank you.

Solution:
Delete the “java.exe” file from “c:\windows” and “c:\windows\system32”. That should fix it.

Libogc 1.8.0 and GRRLib 4.0 issue

Today i have downloaded the newest libogc 1.8.0 library and the newest r18 compiler. For some reason the Vector struct is changes with in the new libogc release. This course the GRRLIB v4.0 library not to compile anymore. Checkout the following link for possible solutions.

Disable Keyboard Break on SUN Ultra

Disable Keyboard Break on SUN Ultra?

Temporary:

# kbd -a disable

Permanent:

Modify the /etc/default/kbd file, by removing the # from the entry:

#KEYBOARD_ABORT=enable

and changing it to:

KEYBOARD_ABORT=disable

SUN Storedge 3310

SUN Storedge 3310 notes:

Management tool for external SCSI disk

# sccli

SCSI Drivers reinit if not visible with format command:

# devfsadm

of

 
# reboot -- -r

UFS format

mkfs -F ufs /dev/rdsk/c2t0d0s2  <LUN 1> <Block amount see format>
mkfs -F ufs /dev/rdsk/c2t0d1s2  <LUN 2> <Block amount see format>
mkfs -F ufs /dev/rdsk/c2t0d2s2  <LUN 3> <Block amount see format>
mkfs -F ufs /dev/rdsk/c2t0d3s2  <LUN 4> <Block amount see format>
mkfs -F ufs /dev/rdsk/c2t0d4s2  <LUN 5> <Block amount see format>

Show SUN hardware PCI info:

# prtconf -v

Show SUN harddisk info

# prtvtoc /dev/dsk/c1t0d0s0

Glassfish notes

Glassfish notes:

# Create new domain3

./asadmin create-domain --adminport 4850 domain3

# Start domain3

./asadmin start-domain domain3

# Stop domain3

./asadmin stop-domain domain3

Mantis compact installation manual

Mantis compact installation manual for Solaris 10

– Patch sun solaris 10.
Install following packages:
– apr-1.2.2
– libintl-3.4.0
– libgcc-3.4.6
– gd-2.0.33

– Install mysql 5.0.24 sun packages
– mysql-5.0.24

– Create mysql user

– Create mantis database

– Create mantis database user with correct rights.

– Install apache 2.X (latest version)
– including PHP module

– Adapted http.conf
– Set correct document root /mantis

– Install start scripts in /etc/rc3.d
– S99apache2
– S99mysql

– Install mantis tar in /usr/local/apache2/htdocs

– Create symlink link mantis to mantis-1.1.7 directory

– Start mysql

– Start apache

– Open browser and enter url: http://localhost

– Fill in database connectie
Database name = mantis
login = mantis
password = mantis

– Mantis database is created

– Remove mantis admin pages
– rm -rf /usr/local/apache2/mantis/admin

– Change administrator password directory (default password = root)

– Now you are ready to us mantis

SUN Jumpstart

SUN jumpstart notes

jumpstart Logging
\var\tmp

Jumpstart activate on source server
ssh
# init 0
telnet -lom
sc> break or on SUN keyboard Stop – A
sc> console -f

ok> boot net – install

or

sc> reset
sc> break (paar keer)
sc> console -f
ok> boot net – install

HAB Add jumpstart Node:
./addhabnode.sh nlnwhabgs03-e0 192.168.0.195 00:03:ba:5a:2c:f9 cm03 gs_prof
./addhabnode.sh nlnwhabwe03-e0 192.168.0.194 00:03:ba:5a:31:6d cm03 we_prof

#CM02
./addhabnode.sh deduhabbe01-e0 10.2.211.4 00:03:ba:5a:2d:21 10.2.211.11 be_prof

HAB Jumpstart flow:
CM01
– in.rarp process
/etc/ethers (MAC -> hostname )
/etc/hosts (hostname -> IP adres)
– inetd deamon must run!
– rpc.bootparam process
/etc/bootparams (IP adres -> hostname)
– tftpboot (Solaris 2.8 Image)

cd /opt/jumpstart/jumpstart
/rules
– hostname -> hab profile
/rules.ok
– Syntax check of rules file.
– run check.sh to create this file.
/ – Create disk partitie
– Install OS
– Delete not needed SUN packages
/complete.sh
– Create jumpstart_profile file
– Set Console cable settings
– Create cmg user
– Set mac address for multipathing
– Set not router
– Copy /config/host file.
– Copy /config/netmasks file.
– Copy /config//defaultrouter file
– Copy /config/snmpd.conf file
– Copy /config/syslog.conf file
– Enable login as root without prompt for password on console
– Disable keyboard break
– Append /usr/local/bin to PATH
– Uncomment SUPATH
– Append /usr/local/sbin and /usr/local/bin to SUPATH
– Make sysidcfg readonly for root
– Set some TCP/IP Settings
– Copy /scripts/general/S99_stage_startup -> /etc/rc2.d
– Copy 0_stage /etc/jumpstart_stage
– Copy /config/bashrc -> .bashrc
– Copy /config/profile -> .profile
– Insert correct hostname in nodename
/scripts/general/security_before.sh
– Allow root to set yp ftp sessions
– Set display locktimeout to 15 minutes
– Set maximun number of login to 5
– Create logfiles for su and login
– Turn off useless lines in inetd.conf
– Set permission and owner of xhost file
– Set kernel parameters
– Prevent IP Spoofing
– Switch off S88sendmail
– reboot

Oracle Enterprise Manager

Oracle Enterprise Manager notes

Start Oracle Enterprise Application Server Manager

./emctl start iasconsole

Note: http://server_name:1158/em

Start Oracle Enterprise Database Manager

./emctl start dbconsole

Note: http://server_name:1158/em

Pong2 on Nokia S60 device

This week i have started with the development of Pong2 for the J2ME platform. I will use the Nokia 5800 as hardware platform and the S60 symbian operating system (Nokia 5800) as target operating system.

The following software tools are used:
– Eclipse Pulsar 3.5
– Nokia S60 5th Edition SDK kit.
– eSWT component palet.

Some background information about the development tools.

Eclipse Pulsar

Pulsar is a tools integration platform for the mobile developer. It make it easy to get the tools and handset SDKs you need for developing mobile applications.

S60 platform overview

The S60 platform is the world’s most popular smartphone platform. It is implemented in a diverse range of devices and provides application and media developers with a consistent set of technologies. Equally at home delivering advanced enterprise applications, games, or music, the S60 platform gives developers unparalleled opportunities in the mobile space.

To create applications, developers can use Symbian C++ (using native Symbian OS and S60 platform APIs), a set of open C and C++ APIs, the Javaâ„¢ language (using MIDP 2.1 with an extensive range of additional JSRs), Web Runtime (WRT) (using standard web technologies), Flash Lite from Adobe, and Python.

In addition, developers may wish to explore the Qt for S60 technology preview, which provides an insight into a new, cross-platform API that will become available on the S60 platform in the future.

Content developers have comprehensive support for audio, image, and video formats. In addition, Flash Lite from Adobe and SVGT can be used for animated content, while the Web Browser for S60 supports standard desktop web technologies. Artists and graphic designers can create themes for S60 devices that can completely alter a device’s look and sound.

Once applications and content have been created, support for OMA DRM protects developers’ intellectual property.

The S60 platform enables developers to create high-value applications and content with lucrative revenue opportunities. The platform approach — with uniform implementation of technologies and supporting tools, documentation, and examples — requires less effort by developers to grasp the biggest market opportunity.

Find out more about the platform’s value proposition to consumer and enterprise users at S60.com, the “one-stop shop” for consumer information on the S60 platform — including applications, licensees, devices, news, and blogs.

eSWT stands for Embedded Standard Widget Toolkit.

It is an open source widget toolkit for Java designed to provide efficient, portable access to the user-interface facilities of the devices on which it is implemented. It is co-developed by Nokia, IBM and others in the eRCP Eclipse foundation project.

It’s API is a subset of desktop SWT API developed also in Eclipse. Additionally eSWT also contains Mobile Extensions for SWT package containing new APIs specially designed for mobile UIs in mind.

For Java ME eSWT provides rich UI functionality:

* rich component set,
* flexible layouts, freely positionable components,
* rich UI events, and
* rich access to native UI functionality on-par with smartphone UI frameworks.

eSWT is designed so that it can both be implemented in CLDC and CDC. It is thus possible to implement that in any Java MIDP device. S60 3rd Edition FP2 will have eSWT accessible in S60 Java for normal MIDlets. In this case it is a complementary UI toolkit for MIDP’s LCDUI toolkit.

eSWT is also integral part eRCP (Embedded Rich Client Platform), a new rich application model being currently developed in Eclipse. In other words eSWT can be a standalone UI toolkit or provided as part of eRCP.

Make eclipse Galileo 3.5 work with a NTMLv2 Proxy

I installed eclipse 3.5 at my work place (where we access internet through an authenticated NTML proxy). I was unable to make eclipse pass through this proxy, which prevented me to install updates and additional software.

Anthony Dahanne’s describes the workaround on his blog (in french). The Apache httpclient implementation should be disabled because it doesn’t work well with NTMLv2 proxies.

For NTLMv2 Proxies, that require user name and password for access the workaround is to

1. Disable the ECF httpclient provider.
2. Provide the NTLMv2 proxy authentication info (proxyhost, domain, username, and password)

In practice, edit your eclipse.ini file to append the following properties.

-Dorg.eclipse.ecf.provider.filetransfer.excludeContributors=org.eclipse.ecf.provider.filetransfer.httpclient
-Dhttp.proxyPort=8080
-Dhttp.proxyHost=myproxy
-Dhttp.proxyUser=mydomain\myusername
-Dhttp.proxyPassword=mypassword
-Dhttp.nonProxyHosts=localhost|127.0.0.1

SUN hardware benchmark

SUN Enterprise 250 / 248 MHZ / 256 MB
[Feb 14 10:01:48 UTC] Automatic processor type detection found an UltraSPARC-II processor.
[Feb 14 10:01:48 UTC] RC5-72: using core #5 (AnBe 2-pipe).
[Feb 14 10:02:07 UTC] RC5-72: Benchmark for core #5 (AnBe 2-pipe) 0.00:00:16.52 [501,916 keys/sec]
[Feb 14 10:02:26 UTC] OGR-P2: Benchmark for core #0 (GARSP 6.0) 0.00:00:16.69 [2,823,340 nodes/sec]

SUN Ultra 10 / 333 MHz / 512 MB
[Feb 14 09:59:21 UTC] Automatic processor type detection found an UltraSPARC-IIi processor.
[Feb 14 09:59:21 UTC] RC5-72: using core #5 (AnBe 2-pipe).
[Feb 14 09:59:39 UTC] RC5-72: Benchmark for core #5 (AnBe 2-pipe) 0.00:00:16.15 [685,418 keys/sec]
[Feb 14 09:59:58 UTC] OGR-P2: Benchmark for core #0 (GARSP 6.0) 0.00:00:16.84 [3,854,463 nodes/sec]

SUN Ultra 10 / 440 MHZ / 512 MB
[May 01 05:29:15 UTC] Automatic processor type detection found an UltraSPARC-IIi processor.
[May 01 05:29:15 UTC] RC5-72: using core #5 (AnBe 2-pipe).
[May 01 05:29:33 UTC] RC5-72: Benchmark for core #5 (AnBe 2-pipe) 0.00:00:16.23 [908,269 keys/sec]
[May 01 05:29:53 UTC] OGR-P2: Benchmark for core #0 (GARSP 6.0) 0.00:00:16.91 [5,123,975 nodes/sec]

SUN Blade 100 / 500 MHz / 512 MB
[Feb 14 09:59:21 UTC] Automatic processor type detection found an UltraSPARC-IIe processor.
[Feb 14 09:59:21 UTC] RC5-72: using core #5 (AnBe 2-pipe).
[Feb 14 09:59:39 UTC] RC5-72: Benchmark for core #5 (AnBe 2-pipe) 0.00:00:16.15 [1,101,418 keys/sec]
[Feb 14 09:59:58 UTC] OGR-P2: Benchmark for core #0 (GARSP 6.0) 0.00:00:16.84 [5,231,463 nodes/sec]

SUN Blade 1000 / 750 MHZ / 1 GB
[May 01 05:34:12 UTC] Automatic processor type detection found an UltraSPARC-III processor.
[May 01 05:34:12 UTC] RC5-72: using core #5 (AnBe 2-pipe).
[May 01 05:34:31 UTC] RC5-72: Benchmark for core #5 (AnBe 2-pipe) 0.00:00:16.21 [1,557,063 keys/sec]
[May 01 05:34:50 UTC] OGR-P2: Benchmark for core #0 (GARSP 6.0) 0.00:00:16.59 [8,394,930 nodes/sec]

SUN Fire 210 / 1 GHZ / 4 GB
[Feb 14 10:15:19 UTC] Automatic processor type detection found an UltraSPARC-IIIi processor.
[Feb 14 10:15:20 UTC] RC5-72: using core #5 (AnBe 2-pipe).
[Feb 14 10:15:38 UTC] RC5-72: Benchmark for core #5 (AnBe 2-pipe) 0.00:00:16.06 [2,079,802 keys/sec]
[Feb 14 10:15:57 UTC] OGR-P2: Benchmark for core #0 (GARSP 6.0) 0.00:00:16.43 [11,217,790 nodes/sec]

SUN Fire 240 / 1 GHZ / 4 GB
[Feb 14 10:05:39 UTC] Automatic processor type detection found an UltraSPARC-IIIi processor.
[Feb 14 10:05:39 UTC] RC5-72: using core #5 (AnBe 2-pipe).
[Feb 14 10:05:58 UTC] RC5-72: Benchmark for core #5 (AnBe 2-pipe) 0.00:00:16.61 [2,088,402 keys/sec]
[Feb 14 10:06:17 UTC] OGR-P2: Benchmark for core #0 (GARSP 6.0) 0.00:00:16.64 [11,263,969 nodes/sec]

MySQL notes

Mysql

#######
Creating MySQL database on Linux system

1. I assume that you are working from your account and not the root. Start a terminal session and become the superuser (Type su at the prompt and then enter the root password).
2. Now we’ll access the MySQL server. Type:

mysql -u root -p

The system prompts for the MySQL root password that you set up in Installing MySQL on Linux. (Note: This is not the Linux root password but the MySQL root password). Enter the password, which is not displayed for security reasons.
Once you are successfully logged in, the system prints a welcome message and displays the mysql prompt … something like

Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1 to server version: 3.22.32

Type ‘help’ for help.

mysql>

3. Now we are ready for creating the employees database. Issue the command:

create database employees;

(Note: The command ends with a semi-colon)

4. An important point to note is that this database is created by the root and so will not be accessible to any other user unless permitted by the root. Thus, in order to use this database from my account (called manish), I have to set the permissions by issuing the following command:

GRANT ALL ON employees.* TO manish@localhost IDENTIFIED BY “eagle”

The above command grants my account (manish@localhost) all the permissions on employees database and sets my password to eagle. You should replace manish with your user name and choose an appropriate password.
5. Close the mysql session by typing quit at the prompt. Exit from superuser and come back to your account. (Type exit).
6. To connect to MySQL from your account, type:

mysql -u user_name -p

Type in the password when prompted. (This password was set by the GRANTS ALL… command above) . The system displays the welcome message once you have successfully logged on to MySQL. Here is how your session should look like:

[manish@localhost manish]$ mysql -u manish -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 3 to server version: 3.22.32

Type ‘help’ for help.

mysql>

7. Typing the command SHOW DATABASES; will list all the databases available on the system. You should get a display similar to:

mysql> SHOW DATABASES;
+—————-+
| Database |
+—————-+
| employees |
| mysql |
| test |
+—————-+
3 rows in set (0.00 sec)

8. Enter quit at the mysql> prompt to come out of the mysql client program.

########
LOAD DUMP

After you have dumped out your data into a file as described here, FTP or scp that dump file to the home directory (/) on our system.

Once you have uploaded the dump file to your account here, get a shell prompt on our system using telnet or ssh.

Now import the dump file into MySQL by typing all the following on 1 single line at the shell prompt:

mysql -p -h DBSERVER dbname < dbname.sql The above assumes that your database name on our system is "dbname" and the dumpfile that you uploaded was named "dbname.sql". Replace those with your correct database name and dumpfile filename. Also replace DBSERVER with your correct database server name. ###### SET OLD PASSWORD Reset the password to pre-4.1 style for each user that needs to use a pre-4.1 client program. This can be done using the SET PASSWORD statement and the OLD_PASSWORD() function: mysql> SET PASSWORD FOR ‘some_user’@’some_host’ = OLD_PASSWORD(‘newpwd’);
mysql> FLUSH PRIVILEGES;

Substitute the password you want to use for “newpwd” in the preceding examples. MySQL cannot tell you what the original password was, so you’ll need to pick a new one.

######
Drop database

Definition: The drop database command is used when you no longer need one of the SQL databases on your server. It will remove it permanently. It is phrased as: drop database [DatabaseName];
Examples: This will remove the database ‘Dresses’ from the MySQL server:

mysql> drop database Dresses;

GRRLIB 4.0 freetype support

In this post i have add information how to add freetype library support to GRRLIB 4.0 library

Add the following source code section in the upper part of the GRRLIB 4.0 C file.

#include &quot;font_ttf.h&quot;

#define DEFAULT_FIFO_SIZE (256 * 1024)

u32 fb = 0;
static void *xfb[2] = { NULL, NULL};
GXRModeObj *rmode;
void *gp_fifo = NULL;

/******************************************************************************/
/**** FREETYPE START ****/
/* This is a very rough implementation if freetype using GRRLIB */

#include  /* I presume you have freetype for the Wii installed */
#include FT_FREETYPE_H

static FT_Library ftLibrary;
static FT_Face ftFace;

void *fontTempLayer=NULL;
void *fontTexture=NULL;

/* Static function prototypes */
static void BitmapTo4x4RGBA(const unsigned char *src, void *dst, const unsigned int width, const unsigned int height);
static bool BlitGlyph(FT_Bitmap *bitmap, int offset, int top, int color) ;

extern void GRRLIB_InitFreetype(void)
{
	unsigned int error = FT_Init_FreeType(&amp;amp;ftLibrary);
	if (error)
	{
		exit(0);
	}

	error = FT_New_Memory_Face(ftLibrary, font_ttf, font_ttf_size, 0, &amp;amp;ftFace);
	if (error == FT_Err_Unknown_File_Format)
	{
		exit(0);
	}
	else if (error)
	{
		/* Some other error */
		exit(0);
	}
}

extern void GRRLIB_initTexture(void)
{
   // Clear previous video frame buffer
   if (fontTexture!=NULL) free(fontTexture);

   fontTempLayer = (void*) calloc(1, 640 * 480 * 4);

   if (fontTempLayer == NULL)
   {
	  /* Oops! Something went wrong! */
	  exit(0);
   }
}

extern void GRRLIB_Printf2(int x, int y, const char *string, unsigned int fontSize, int color)
{
	unsigned int error = 0;
	int penX = 0;
	int penY = fontSize;
	FT_GlyphSlot slot = ftFace-&amp;gt;glyph;
	FT_UInt glyphIndex = 0;
	FT_UInt previousGlyph = 0;
	FT_Bool hasKerning = FT_HAS_KERNING(ftFace);

    error = FT_Set_Pixel_Sizes(ftFace, 0, fontSize);
	if (error)
	{
		/* Failed to set the font size to the requested size.
		 * You probably should set a default size or something.
		 * I'll leave that up to the reader. */
		 FT_Set_Pixel_Sizes(ftFace, 0, 12);
	}

	/* Convert the string to UTF32 */
	size_t length = strlen(string);
	wchar_t *utf32 = (wchar_t*)malloc(length * sizeof(wchar_t));
	length = mbstowcs(utf32, string, length);

	/* Loop over each character, drawing it on to the 4, until the
	 * end of the string is reached, or until the pixel width is too wide */
	unsigned int loop = 0;
	for (loop = 0; loop &amp;lt; length; ++loop)
    {
		glyphIndex = FT_Get_Char_Index(ftFace, utf32[ loop ]);

		/* To the best of my knowledge, none of the other freetype
		 * implementations use kerning, so my method ends up looking
		 * slightly better 🙂 */
		if (hasKerning &amp;amp;&amp;amp; previousGlyph &amp;amp;&amp;amp; glyphIndex)
		{
			FT_Vector delta;
			FT_Get_Kerning(ftFace, previousGlyph, glyphIndex, FT_KERNING_DEFAULT, δ);
			penX += delta.x &amp;gt;&amp;gt; 6;
		}

		error = FT_Load_Glyph(ftFace, glyphIndex, FT_LOAD_RENDER);
		if (error)
        {
			/* Whoops, something went wrong trying to load the glyph
			 * for this character... you should handle this better */
			continue;
		}

		if (BlitGlyph(&amp;amp;slot-&amp;gt;bitmap, penX + slot-&amp;gt;bitmap_left+x, penY - slot-&amp;gt;bitmap_top+y, color) == true)
		{
			/* The glyph was successfully blitted to the buffer, move the pen forwards */
			penX += slot-&amp;gt;advance.x &amp;gt;&amp;gt; 6;
			previousGlyph = glyphIndex;
		}
		else
		{
			/* BlitGlyph returned false, the line must be full */
			free(utf32);
			return;
		}
	}

	free(utf32);
}

/* Returns true if the character was draw on to the buffer, false if otherwise */
static bool BlitGlyph(FT_Bitmap *bitmap, int offset, int top, int color)
{
	int bitmapWidth = bitmap-&amp;gt;width;
	int bitmapHeight = bitmap-&amp;gt;rows;

	if (offset + bitmapWidth &amp;gt; 640)
	{
		/* Drawing this character would over run the buffer, so don't draw it */
		return false;
	}

	/* Draw the glyph onto the buffer, blitting from the bottom up */
	/* CREDIT: Derived from a function by DragonMinded */
	unsigned char *p = fontTempLayer;
	unsigned int y = 0;
	for (y = 0; y &amp;lt; bitmapHeight; ++y)
	{
		int sywidth = y * bitmapWidth;
		int dywidth = (y + top) * 640;

		unsigned int column = 0;
		for (column = 0; column &amp;lt; bitmapWidth; ++column)
        {
			unsigned int srcloc = column + sywidth;
			unsigned int dstloc = ((column + offset) + dywidth) &amp;lt;&amp;lt; 2;

			/* Copy the alpha value for this pixel into the texture buffer */
			p[ dstloc + 0 ] = (color &amp;amp; 0xff);
			p[ dstloc + 1 ] = ((color &amp;gt;&amp;gt; 8) &amp;amp; 0xff);
			p[ dstloc + 2 ] = ((color &amp;gt;&amp;gt; 16) &amp;amp; 0xff);
			p[ dstloc + 3 ] = (bitmap-&amp;gt;buffer[ srcloc ]);
		}
	}

	return true;
}

/* Render the text string to a 4x4RGBA texture, return a pointer to this texture */
extern void* GRRLIB_GetTexture(void)
{
	/* Create a new buffer, this time to hold the final texture
	 * in a format suitable for the Wii */
	fontTexture = memalign(32, 640 * 480 * 4);

	/* Convert the RGBA temp buffer to a format usuable by GX */
	BitmapTo4x4RGBA(fontTempLayer, fontTexture, 640, 480);
	DCFlushRange(fontTexture, 640 * 480 * 4);

	/* The temp buffer is no longer required */
	free(fontTempLayer);

	return fontTexture;
}

static void BitmapTo4x4RGBA(const unsigned char *src, void *dst, const unsigned int width, const unsigned int height)
{
	unsigned int block = 0;
	unsigned int i = 0;
	unsigned int c = 0;
	unsigned int ar = 0;
	unsigned int gb = 0;
	unsigned char *p = (unsigned char*)dst;

	for (block = 0; block &amp;lt; height; block += 4) {
		for (i = 0; i &amp;lt; width; i += 4) {
			/* Alpha and Red */
			for (c = 0; c &amp;lt; 4; ++c) {
				for (ar = 0; ar &amp;lt; 4; ++ar) {
					/* Alpha pixels */
					*p++ = src[(((i + ar) + ((block + c) * width)) * 4) + 3];
					/* Red pixels */
					*p++ = src[((i + ar) + ((block + c) * width)) * 4];
				}
			}

			/* Green and Blue */
			for (c = 0; c &amp;lt; 4; ++c) {
				for (gb = 0; gb &amp;lt; 4; ++gb) {
					/* Green pixels */
					*p++ = src[(((i + gb) + ((block + c) * width)) * 4) + 1];
					/* Blue pixels */
					*p++ = src[(((i + gb) + ((block + c) * width)) * 4) + 2];
				}
			}
		} /* i */
	} /* block */
}

inline void GRRLIB_DrawImg2(f32 xpos, f32 ypos, u16 width, u16 height, u8 data[], float degrees, float scaleX, f32 scaleY, u8 alpha )
{
   GXTexObj texObj;

	GX_InitTexObj(&amp;amp;texObj, data, width,height, GX_TF_RGBA8,GX_CLAMP, GX_CLAMP,GX_FALSE);
	//GX_InitTexObjLOD(&amp;amp;texObj, GX_NEAR, GX_NEAR, 0.0f, 0.0f, 0.0f, 0, 0, GX_ANISO_1);
	GX_LoadTexObj(&amp;amp;texObj, GX_TEXMAP0);

	GX_SetTevOp (GX_TEVSTAGE0, GX_MODULATE);
  	GX_SetVtxDesc (GX_VA_TEX0, GX_DIRECT);

	Mtx m,m1,m2, mv;
	width *=.5;
	height*=.5;
	guMtxIdentity (m1);
	guMtxScaleApply(m1,m1,scaleX,scaleY,1.0);
	Vector axis =(Vector) {0 , 0, 1 };
	guMtxRotAxisDeg (m2, &amp;amp;axis, degrees);
	guMtxConcat(m2,m1,m);

	guMtxTransApply(m,m, xpos+width,ypos+height,0);
	guMtxConcat (GXmodelView2D, m, mv);
	GX_LoadPosMtxImm (mv, GX_PNMTX0);

	GX_Begin(GX_QUADS, GX_VTXFMT0,4);
  	GX_Position3f32(-width, -height,  0);
  	GX_Color4u8(0xFF,0xFF,0xFF,alpha);
  	GX_TexCoord2f32(0, 0);

  	GX_Position3f32(width, -height,  0);
 	GX_Color4u8(0xFF,0xFF,0xFF,alpha);
  	GX_TexCoord2f32(1, 0);

  	GX_Position3f32(width, height,  0);
	GX_Color4u8(0xFF,0xFF,0xFF,alpha);
  	GX_TexCoord2f32(1, 1);

  	GX_Position3f32(-width, height,  0);
	GX_Color4u8(0xFF,0xFF,0xFF,alpha);
  	GX_TexCoord2f32(0, 1);
	GX_End();
	GX_LoadPosMtxImm (GXmodelView2D, GX_PNMTX0);

	GX_SetTevOp (GX_TEVSTAGE0, GX_PASSCLR);
  	GX_SetVtxDesc (GX_VA_TEX0, GX_NONE);

}

/**** WVDP: FREETYPE END ****/
/******************************************************************************

Add the following part in the GRRLIB.h file

/**** WVDP: FREETYPE START ****/
extern void GRRLIB_InitFreetype();
extern void GRRLIB_initTexture(void);
extern void GRRLIB_Printf2(int x, int y, const char *string, unsigned int fontSize, int color);
extern void* GRRLIB_GetTexture(void);
inline void GRRLIB_DrawImg2(f32 xpos, f32 ypos, u16 width, u16 height, u8 data[], float degrees, float scaleX, f32 scaleY, u8 alpha );
/**** WVDP: FREETYPE END ****/

For example how to use this extension, please download the RedSquare source code.
Good Luck with it ❗ If you have any questions, please post a comment.

Show JPG image on Wii screen

The following function shows a jpg image.

void drawJpegImage(char *pictureData, int pictureLength, int x, int y )
{
  JPEGIMG         jpeg;
  int             row,
  col,
  pix,
  offset;
  unsigned int   *jpegout;

  memset(&amp;jpeg, 0, sizeof(JPEGIMG));

  jpeg.inbuffer = pictureData;
  jpeg.inbufferlength = pictureLength;

  JPEG_Decompress(&amp;jpeg);

  pix = 0;

  jpegout = (unsigned int *) jpeg.outbuffer;

  offset=(y+yjpegOffset)*320;
  for (row = 0; row &lt; jpeg.height; row++)
  {
      for (col = 0; col &lt; (jpeg.width &gt;&gt; 1); col++)
      {
         frameBuffer[0][offset + col + x] = jpegout[pix++];
      }
      offset+=320;
  }

  free(jpeg.outbuffer);
}

Compiled Libogc 1.7.1

To help beginner Wii developers i have compiled the latest available libogc 1.7.1 library. I have added to this library libfat 1.0.2 and libsnd 1.0. Please click on the below link to download this library.

Update on 06-02-2010. I removed the download link. Now libogc 1.8.1 with integrated sound module is available. So there is not need anymore for this download!

Wii network library

The following Wii network library was developed by dhewg, and adapted by me. This library also contain functionality to log the start of an application. This event with optional user data (for example highscore information) is send to Google analytics.

Short API description

# Start http / tcp thread
extern int tcp_start_thread(char *name, char *version, char *id1, char *url1, char*id2, char *url2, char *id3, char *url3, char *token, char *userData2, char *userData3);

# Stop network thread
extern int tcp_stop_thread(void);

# Get current state of network statemachine as digit
extern int tcp_get_state_nr(void);

# Get current state of network statemachine as text label
extern char *tcp_get_state(void);

# Set new state 
int tcp_set_state(int state, char *userData3);

# Get newest application version from a webpage.
extern char *tcp_get_version(void);

# Get release notes information from a webpage.
extern char *tcp_get_releasenote(void);

# Get highscore xml information from a webservice.
extern char *tcp_get_highscore(void);

Download

You can download this library be click to below link.

See for a working example the Pong2, BibleQuiz, RedSquare or SpaceBubble source code.