Linux as home desktop, why not?

Linux is a free stable and resourcefull operating system yet to prove it’s full potential as a desktop operating system. While the greater part of the market is still Windows based the introduction of the UMPC (Ultra Mobile PC) have turned things upside down for Microsoft. Instead of buying very expensive hardware and install Vista many choose to buy less hardware and get either a Linux distribution or (even worse?) a several years old Windows XP system.  Microsoft was not prepared for this turn of events and have been forced to extend the lifespan of their XP-series which they where planning to phase out in favour of Vista.

This change in consumer behaviour to “not buy the best” anymore, have favoured Linux who with their versatile distributions have a stable modern operating system for just about any new or old hardware out there. My five year old laptop which where being exhausted by running Windows XP in combination with a virus tool runs perfectly smooth with the Ubuntu distribution (well I could theoritically run XP without a virus tool but seeing I travel alot with it that would just be beging for it to crash with all the unsecure networks I connect to).

With the UMPC Linux have gained a small part of the desktop market, but what is holding it back to take an even larger part? Is it the hardware support? Well granted some hardware vendors only supply drivers for Windows systems, but most hardware have at least decent support in Linux. Is it Internet related software? Hardly, Firefox is arguably better than the current version of Internet Explorer (granted Firefox is available on both systems) and also e-mail clients like Thunderbird are just as easy as Outlook Express to setup. Are the office tools sub standard? Open Office and GIMP make a very good competition for their commercial counterparts Microsoft Office and Adobe Photoshop, so except for prior experience in one system there really is no major difference for the home desktop user there. Is it the ease of use? Again, trying out Vista will be just as confusing for a XP user as it would be switching to Ubuntu. Most things have changed places anyway. Also the update feature in Ubuntu is much better than Windows update in my opinion. The ability to upgrade all installed applications through a common interface is very easy to handle for an inexperienced user.

There is one single left over reason that I see quoted time and time again: “I use Windows XP becuase I want to play games”.

Is there any major reason to hold back? Well… I have to say yes. There is one single left over reason that I see quoted time and time again: “I use Windows XP becuase I want to play games”. Almost no PC game whatsoever have Linux-support. There are, often technical, HOWTOs on how to get this or that game running under Linux but it usually involves pages of instructions. If we have everything else, surely games can’t make a major difference for a desktop operating system? Again, I’d have to say yes it does. Why? Simple, the kid in the family who usually is the computer wiz is the one who helps all his family and friends install their computers. If this kid runs XP back home to play computer games on he will install XP on all other machines, because this operating system he knows and can “support”. Furthermore if all else being equal, if there is one major drawback in a single area, whoever wins that will probably win the battle.

Windows XP have DirectX which is supported and used by I would dare say every game manufacturer for the PC market. Linux have no equivalent interface. Linux have “emulated” Windows and even tried to port games individually but the major all-supported interface is not there. Game companys can’t make a release for every distribution out there (since many are so different it would be required), but if a common interface for all distributions could be established that would increase the chances of Linux game releases.

In my opinion, this is one of the major reasons Linux is still held back as a desktop operating system. Far from the only reason, but a major one.

Zombie safe homepage

It’s been a while since I had time to post some useful information here, meanwhile so you don’t turn into zombies or even worse get attacked by them here is some helpfull code from Google themselves:

http://www.google.com/robots.txt

And, just in case they change the file, here are the top lines from their robots.txt:

User-agent: zombies
Disallow: /brains

User-agent: *
Allow: /searchhistory/
Disallow: /news?output=xhtml&
Allow: /news?output=xhtml
Disallow: /search
...

Having fun with the WordPress Database

Today I’ve improved the starting page of this domain, www.fireflake.com. It looked very booring and I thought I’d have to do something with it but at the same time I knew I was to lazy to acctually maintain some interesting subjects there as well. The solution was simple! Use my blogs to feed the information to the starting page! Here are some of my php and sql code used, in case you want to try something similar yourself.

First of all, if you’ve never done any PHP before, do not fear, it’s super easy! Without explaining it, here are my open and close database files (I keep them seperate since they will most likely be included in many pages):

open_db.php:

<?php
$dbhost = ‘localhost’;
$dbuser = ‘username’;
$dbpass = ‘password’;

$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die                      (‘Error connecting to mysql’);

$dbname = ‘dbname’;
mysql_select_db($dbname);
?>

close_db.php:

<?php
mysql_close($conn);
?>

Just modify these files with the values for your database and you are ready to do some mysql-powered-php-scripting! Next simply include these files in the file where you want to use the database, in my example index.php:

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Strict//EN” “http://www.w3.org/TR/html4/strict.dtd”>
<?php include ‘open_db.php’; ?>
<html>

</html>
<?php include ‘close_db.php’; ?>

Now lets make the MySQL database print something to the index-page! Here is an example:

<?php
$query  = “select now() as mysqltime”;
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo $row[‘mysqltime’];
}
?>

This will print a timestring from your MySQL. I used this as an example just because it should work everywhere. Now simply substitute the query with something you want from your database and the printout inside the loop with what (and how) you want it printed!

To take a WordPress example, I want to use the tags/categories as keywords for the META-tag of my start page. I use a cleaverly written SQL query that will give me all the unique keywords for all my three blogs sorted in order of usage:

<?php
$query  = “SELECT name,`count` FROM tech_terms t join tech_term_taxonomy tt on (t.term_id = tt.term_id)
union distinct
SELECT name,`count` FROM game_terms t join game_term_taxonomy tt on (t.term_id = tt.term_id)
union distinct
SELECT name,`count` FROM 3wp_terms t join 3wp_term_taxonomy tt on (t.term_id = tt.term_id)
order by `count` desc limit 0,50;”;
$result = mysql_query($query);
$keywords = array();
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
array_push($keywords,$row[‘name’]);
}
$keywords = array_unique($keywords);
foreach ($keywords as $key){
$meta_key_string .= $key.”,”;
}
?>
<meta name=”keywords” content=”<?php echo $meta_key_string ?>fireflake”>

This will make my home meta tag always up to date with what I write about! The keywords will also be listed in order of relevance since they are ordered by “count” from the database.

Another great little script takes out the latest posts in a blog and prints them (and links it to the main article):

<?php
$query  = “select * from tech_posts where post_status = ‘publish’ order by post_date desc limit 0,2”;
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo “<h3><a href=”” . $row[‘guid’] . “”>” . $row[‘post_title’] .”</a></h3>”;
echo “<p>” . str_replace(“n”,”<br />n”,$row[‘post_content’]) .”</p><br clear=”all”>”;
}
?>

There are probably lots of fun you can have with the WordPress database, it’s very simple and easy to learn so it’s very easy to start writing code like this!

Hope you found something useful here!

Using PHP to check response time of HTTP-server

I must start off with admiting that my PHP skills are very limited, however being a very experienced Perl hacker this is very similar to me. Edit 2013-01-30: This is no longer true 🙂

I needed a script that checked for a normal HTTP response from another server, a status script to see if the other server(s) where behaving as they should.

The resources on-line for PHP are great and I quickly found the code needed to retrieve a remote page and read the contents. I also found some tutorials describing how to use this code. My version ended up looking like this (thanks phptoys.com for the tutorial!):

<?php
// check responsetime for a webbserver
function pingDomain($domain){
    $starttime = microtime(true);
    // supress error messages with @
    $file      = @fsockopen($domain, 80, $errno, $errstr, 10);
    $stoptime  = microtime(true);
    $status    = 0;

    if (!$file){
        $status = -1;  // Site is down
    }
    else{
        fclose($file);
        $status = ($stoptime - $starttime) * 1000;
        $status = floor($status);
    }
    return $status;
}
?>

What this code does is to measure, using the microtime function, the time difference between initiating a connection using fsockopen and when that functions has completed executing. If a connection was established the time difference is returned. If fsockopen failed to open a connection -1 is returned.

The time difference is multiplied by 1000 to get the number of milliseconds it took, floor() is then used to round down to the nearest integer value.

To call this function simply add the domain or IP you want to check the response time of:

Fireflake: <?php echo pingDomain('tech.fireflake.com'); ?> ms<br>
Example: <?php echo pingDomain('www.example.com'); ?> ms<br>
Internal IP: <?php echo pingDomain('192.168.0.2'); ?> ms<br>
Fail: <?php echo pingDomain('fail.fireflake.com'); ?> ms<br>

Sample output from the above statements are:

Fireflake: 111 ms
Example: 139 ms
Internal IP: 0 ms
Fail: -1 ms

Also, sometimes DNS servers return a “search engine” response if the domain is unknown or unreachable. To be sure you reach the server you want try calling it by IP-number instead to make sure your DNS isn’t fooling you.

EDIT:  Thx for adding the tip to use @ to supress error messages. Just use @fsockopen to supress the inevitable error message.

EDIT 2013-01-30: Fixed the old code and added some more examples.

EDIT 2013-03-07: Added clarification about unit used in $status.

Using AJAX to asynchronously load slow XML files

More and more I’ve come across situations where I want to use AJAX to download a XML file to use in the interface but know beforhand that the file will take a long time to load. With asyncroneous download of XML files by JavaScript, which is kind of what the buzz word AJAX is all about, you must be carefull not to leave the client in limbo between a useable interface and a locked up screen.

Unfortunately this script only works in Internet Explorer, useful tips of how to port it properly (with the asynchronous property intact) would be highly appreciated.

Here is a simple description of the basic functions needed to perfom a asynchronous download where the user will have the option to abort.

First we need a simple function that download the XML, this is pretty standard and the code is lovingly ripped off from w3school.com.

function loadXml(sUrl){
	try{
		//Internet Explorer
		xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
	}
	catch(e){
		try{
			//Firefox, Mozilla, Opera, etc.
			xmlDoc = document.implementation.createDocument("","",null);
		}
		catch(e) {
			alert(e.message)
		}
	}
	try{
		xmlDoc.async = 'true';
		xmlDoc.load(sUrl);
	}
	catch(e) {
		alert(e.message)
	}
}

This code is pretty straight forward and I assume you allready know of it, if not read the guide over at W3Schools. The only difference in the above code compared to that from the tutorial over at W3Schools is the flag “xmlDoc.async = ‘true'”. This means that the code will continue executing after the load is called without waiting for the load to finish. This will place the status of the xmlDoc variable in a limbo which can be checked with the “readyState” flag.

To check if our file is ready to use we have a test-loop that will check if readyState changes:

function testReadyLoop(){
	i++;
	if (xmlDoc.readyState == 4){
		// the file has completed the download
		alert('xmlDoc ready to use! Contents:n' + xmlDoc.xml);
		// TODO: add code here of what to do with the file
	}
	else{
		if (!abortXmlLoad){
			// try again in 1 second
			setTimeout("testReadyLoop();",1000);
		}
		else{
			// stop loading the xml file
			xmlDoc.abort();
			alert('Loading of the XML file aborted!');
		}
	}
}

The incrementation of the variable “i” is just a counter that will be used later and the “abortXmlLoad” is a boolean if the loop should continue or not, these will be explained later. What happens in this function is that it first tests if readyState is 4 which indicates that the file is ready to be used, if this is the case we simple show an alert with the contents of the file, here more intelligent code would be placed. If it’s not ready it checks if it should continue waiting for the file or not, if it should it calls itself in 1 second (1000 ms) otherwise it aborts the loading and simply stops.

To abort a download we need to set the “abortXmlLoad” flag to true, a short function is needed for this:

function abortAsyncXML(){
	// set the abort flag to true
	abortXmlLoad = true;
}

Now we have all the functions needed for the asynchronous download, a last function is added to tie them all togheter:

function loadAsyncXML(sUrl){
	// set abort to false and start download
	abortXmlLoad = false;
	i = 0;
	loadXml(sUrl);
	// start loop to check when ready
	testReadyLoop();
}

This function first resets the values of “i” and “abortXmlLoad” and then it calls the download and after that starts the loop to test if the download is ready. The file will now download silently in the background and pop an alert when ready unless someone calls “abortAsyncXml” before that happens.

As you may have noticed there are a few global variables I use across the functions that also need to be added to the top of the script:

var xmlDoc;
var abortXmlLoad;
var i;

To use this script a small form need to be added to the page:

<form>
<input type="button" value="load" onclick="loadAsyncXML('sample.xml');">
<input type="button" value="abort" onclick="abortAsyncXML();">
</form>

This will load the file “sample.xml” and abort if the abort button is pushed. In order to test that the abort button is working you would have to build a slow loading page that simulates long loading time.

I will post a link to the full code and sample later. Hope you found this helpful.

Are you not (yet) against software patents?

Are software patents protecting the inventors and is something needed to protect intelectual property?

Read this: http://news.zdnet.com/2424-9595_22-218626.html

If it designed to be used to protect intelectual property then it is now abused by large companies for making absurd claims, in this case Microsoft.

Makes me want to patent the “O”-button… peple cant write blgs withut it.

Google Blueprint CSS tutorial

This is a basic tutorial of the first use of Google Blueprint as a CSS layout.

Download Blueprint CSS
Download the main library att Google Code, at the time of this writing that is the file “Blueprint 0.7.1.zip”.
http://code.google.com/p/blueprintcss/downloads/list

There are three folders in the ZIP-file, first you have the “blueprint” folder which contains the ready to use CSS-files (ie.css, print.css and screen.css). While there are more files in that folder we will only concern ourselves with those in directly in the “blueprint” folder and not subfolders.

I will not go into detail about the two other folders, for your information the “lib” folder contains YAML source for the project and the last folder “tests” contains sample pages you can play around with if you’d like.

Fast reference PDF
There is a nice “cheat page” you can print out from a PDF, this is optional though but I found it very helpfull at least while learning the new classes.

Link the CSS-files
All you need to do is copy the three CSS-files in the “blueprint” folder into a directory of your choice in the main HTTP directory. I assume you put them in a subdirectory simply called “blueprint”. Next you need to link them in the HTML-files where you wish to use them, add the following code:

<link rel=”stylesheet” href=”blueprint/screen.css” type=”text/css” media=”screen, projection”>
<link rel=”stylesheet” href=”blueprint/print.css” type=”text/css” media=”print”>
<!–[if IE]><link rel=”stylesheet” href=”blueprint/ie.css” type=”text/css” media=”screen, projection”><![endif]–>

The first CSS defines how to display the page on normal monitors and projectors. The second file is for printing and the last file, surrounded with an IF condition to only be used by Internet Explorer, is specific instructions for the naughty web browsers that do not follow the standards.

Make a HTML file that uses the Blueprint
I assume you know HTML and CSS so I skip the basics and move straight to the new classes that blueprint offers. Simply put you need an outer DIV of the class “container” that will be the parent object of all others. Inside of this you can decleare HTML code as normal. A real simple first page could look something like this:

<div class=”container”>
<div class=”span-24 last”>
<h1>Hello World</h1>
</div>
</div>

The outer DIV is the container of all objects. The second div defines itself as a “span-24” and “last” class. Span-24 is the max width (950 pixels) and will span the entire area inside the container, last is added to signal this is the final column on this row (it’s also the only so in this case maybe a bit overkill).

Now after this it’s very easy to expand the concept, for example to make a “top headline and under menu + content” layout simply write:

<div class=”container”>
<div class=”span-24 last”>
<h1>Hello World</h1>
</div>
<div class=”span-4″>
The menu
</div>
<div class=”span-20 last”>
The content
</div>
</div>

This still doesn’t solve the more complex aspects of CSS-layout when you need everything to be “just right” but with an overall layout made this easy you can focus on the end tweaking instead of re-inventing the basic wheel everytime you need to make a new design.

Conclusion
The absolute best part about the Blueprint CSS is a “small” feature internally namned “rest.css” which is part of the “screen.css” file. This resets all browser settings to one single setting (Firefox, Internet Explorer etc all have slightly different default values for border, margins, padding etc) making cross platform development much much easier. Secondly, and the acctual main purpose, the ability to easily create new columns and layout modifications really improves start up development time of new designs. While the Blueprint CSS just have very basic settings it’s often these basic settings that screw up every new design I make since I tend to aim a little too high everytime I write a new CSS-class.