Archive for the ‘Code examples’ Category

Creating a single line text file from DOS

Friday, April 25th, 2008

I recently had the need to write a batch file that wrote a single line of text to a file for processing by an application. I used the DOS command ‘ECHO’ and directed the output to file, however this wasn’t working and after a bit of troubleshooting I discovered that the resulting file couldn’t end with a new line.

At first I thought this could be a DOS/UNIX issue and ran a simple command-line application (DOS2UNIX) to convert my newlines to a format suitable for Unix based machines. Unfortunately this wasn’t good enough and I needed to find a way of removing the new line from my file. Eventually I found another simple application named CHANGE, which allows you to find and replace characters within files from the command line.

As the characters I needed to replace were a space and the carriage return/line feed I needed to be able to specify the characters as bytes. CHANGE.COM is able to do this, so the following command enabled me to remove the trailing new line:

CHANGE MYFILE.TXT 32,13,10 ""

The CHANGE.COM file can be downloaded from here.

Update: I found a Windows Script that will remove the line here, but have instead written a script that replaces the batch file.

Object Oriented Programming Tutorial

Friday, February 15th, 2008

As I didn’t do a computer science degree, I skipped object oriented programming basics and although I do a reasonable amount of development work I generally work ‘by example’ and certainly haven’t done any C# or Java. As I have some time on my hands at the moment I decided to check out a very simple and easy to follow tutorial to fill in some gaps in my knowledge. Thanks to a quick search I found this tutorial, which is quick and easy to follow. It’s certainly given me a thirst for more knowledge, but the hardest thing is coming up with a project and deciding on a programming language. I have a friend that has an open-source application so perhaps I’ll try to make sense of that and maybe even contribute!

Javascript countdown then redirect

Wednesday, October 24th, 2007

Today I needed to write a simple piece of javascript that counts down and then submits a form. This could easily be adapted to count down before redirecting to another website. Below is sample code that you can add to any page, which counts down from 10 and then displays a message to the user. The countdown is displayed on the page.

Add this to the <head> section of the page:
<script>
<!--
function startCount() {
var countfrom=10 // this controls what number to start counting from
var countnow=document.getElementById('mySeconds').innerHTML=countfrom+1
countAction(countnow)
}

function countAction(countnow) {
if (countnow!=1) {
countnow-=1
document.getElementById(’mySeconds’).innerHTML=countnow;
} else {
alert(’BOOM!’);
return
}
setTimeout(”countAction(”+countnow+”)”,1000)
}
//–>
</script>

Add this to the <body> section:
<p>This page will self destruct in <span id="mySeconds">10</span> seconds...</p>

In order for the counter to start you will need to call the function startCount. You can do this when the page loads by adding onload="javascript:startCount();" to the <body> like below:
<body onload="javascript:startCount();">

Example: Click here to see this in action.

Schedule cPanelX database backups

Monday, October 8th, 2007

Yesterday my flatmate’s website host upgraded his version of MySQL and didn’t think to bring the tables to the new version. It’s easy to tell him that he should have a recent backup (he did, actually) but it got me thinking about a database I set up for CLEIS recently, which wasn’t being backed up at all…

Within about 20 minutes I had a daily backup running that will e-mail me the compressed SQL for the entire database. This uses a PHP file (stored outside the public_html directory for security reasons) that retreives and e-mails the database backup from the cPanelX control panel provided by my host.

Here is the contents of backup.php:

<?php
// Ignore all headers
#!/usr/local/bin/php -q

function get_db_file($db, $domain, $username, $password) {

  // Construct URL from segments
  $url = ‘http://’ . $username . ‘:’ . $password .’@’. $domain .’/getsqlbackup/’. $db .’.gz’;

  // Get the contents of the file
  return(file_get_contents($url));
}

function email_db_file($to, $from, $subject, $message) {
  global $db, $domain, $username, $password;
  $unique_sep = md5(uniqid(time()));

  // Set the e-mail headers
  $headers .= “From: $from\n”.
  “MIME-Version: 1.0\nContent-Type: multipart/mixed;boundary=\”$unique_sep\”;\n”.
  “charset=\”iso-8859-1\”\nContent-Transfer-Encoding: 7bit\n\n” .
  “–$unique_sep\n”.
  “Content-Type: text/plain; charset=\”iso-8859-1\”\n”.
  “Content-Transfer-Encoding: 7bit\n\n”.
  $message.”\n\n”.
  “–$unique_sep\n”.
  “Content-Type: gz; name=\”$db.gz\”\n”.
  “Content-Transfer-Encoding: base64\n”.
  “Content-Disposition: attachment\n\n”;

  // Use earlier function to get database file
  $file = get_db_file($db, $domain, $username, $password);

  // Attach the file to the e-mail
  $headers .= chunk_split(base64_encode($file)) . “–$unique_sep–\n”;

  // Send the e-mail
  if(mail($to, $subject, $message, $headers)) {
    return true;
  } else {
    return false;
  }
}

// Database name
$database_name = “db”;

// Domain name
// Make sure you include the port (:2082) for cPanelX.
$domain = “example.com:2082″;

// cPanelX username and password
$username = “username”;
$password = “password”;

// Address to send the backup file to
$email = “email@example.com”;

// Address the backup will be sent from
$from = “backups@example.com”;

// Call the function to send the e-mail
send_db_file($email, $from, $db .” Database Backup:”, “The scheduled backup of “. $db .” was performed at “. date(”g:i A F j, Y”));
?>

You’ll then need to set up a cron job in cPanelX to run the command php -q /home/[username] /backup.php on whatever schedule you need. You could even set up a second or third cron job to run on different schedules so that you can easily organise multiple generations of backups.

Creating a Table of Contents in XSL:FO

Thursday, August 16th, 2007

Yesterday I needed to produce a table of contents for a PDF file generated using Apache FOP. First of all I got in a mess over list-items where the my page numbers were underneath my titles and unreadable. I then moved onto using leading and justification to produce a perfect table of contents look. I have pasted an example of this technique below.

<xsl:for-each select="entry">
<fo:block text-align-last="justify">
<xsl:value-of select="title"/>
<fo:leader leader-pattern="dots"/>
<fo:page-number-citation ref-id="{@id}"/>
</fo:block>
</xsl:for-each>