Notice: Undefined index: HTTP_ACCEPT_LANGUAGE in /var/www/_lib/language.php on line 6

Notice: Undefined variable: language in /var/www/_lib/language.php on line 16
Portfolio : Code Samples : Rob Lindman: Software Developer

Portfolio

Code Samples

This section contains code samples written by me, in a variety of formats and languages. Later, I plan to convert these to tutorials, and add some more useful information, or have fully functional frameworks here. For now, I have simply accumulated some of my recent developments, and constructed some code to demonstrate my methodology.

This is a work in progress, I will be updating this regularly along with the rest of my site. If something is not immediately to your liking, feel free to let me know and I will consider it in future revisions of this document.

Javascript

This example sets up a poll which requests information from a php backend. The php backend is a proxy which parses xml feed data and returns the latest headline.

  • This example requires no frameworks or additional libraries, simply a document with a proper div and a script tag
  • If new data appears on the server, this code would populate the document elements with the announcement data, and make the announcement visible.
  • it is written to be referenced externally in it's own .js file.
  • A working demonstration of the system can be arranged upon request.

Source Code


			window.notify = (function() {

				var inMessage = function() {
					var title = "";
					var description = "";
					var date = "";
					var link = "";
					var image = "";
				}

				//

				var REFRESH_PERIOD = 60000;
				var url = "notify.php";

				var oHttp = false;

				var thisTimerID;
				var pollStarted = false;

				var thisMessage = new inMessage();
				var oldMessage = new inMessage();

				//

				safeAddEvent(window, 'load', startPoll);

				//

				function startPoll() {
					if (initHttp()) {
						thisTimerID = setInterval(pollNotification, REFRESH_PERIOD);
						pollNotification();
					}
				}

				function stopPoll() {
					Log('HALTING');
					clearInterval(thisTimerID);
				}

				//

				function initHttp()
				{
					getHttp();

					if (!oHttp) {
						 Log('FAILED: Cannot create XMLHTTP object');
						 return false;
					}

					Log('http object success');
					oHttp.onreadystatechange = OnNotification;

					return true;
				}

				//

				function pollNotification() {

					if (window.ActiveXObject) initHttp();

					var _t = convertOldTime();
					if (isNaN(_t)) _t = 0;
					var _u = url + "?t=" + _t;

					if (!pollStarted) {
						pollStarted = true;
						_u = url;
					}

					Log('polling: ' + _u);

					oHttp.open('GET', _u, true);
					oHttp.send(null);
				}


				function OnNotification() {

					if (oHttp.readyState != 4) return;

					switch (oHttp.status)
					{
						case 304:
							Log('304: not a new notification');
							return;
							break;

						case 200:
							Log('notification received');

							// notification contains no data
							if (oHttp.responseText.length == 0) {
								Log('no data');
								return;
							}

							Log('-----data-------');
							Log(oHttp.responseText);
							Log('-----end--------');

							// localize the message
							var _tmp = oHttp.responseText.split("\n");

							// bad data
							if (_tmp.length < 4) {
								Log('invalid data');
								return;
							}

							thisMessage.title = _tmp[0];
							thisMessage.description = _tmp[1];
							thisMessage.link = _tmp[2];
							thisMessage.date = _tmp[3];

							Log('-----parsed-----');
							Log('title: ' + thisMessage.title);
							Log('description: ' + thisMessage.description);
							Log('link: ' + thisMessage.link);
							Log('date: ' + thisMessage.date);
							Log('-----end--------');

							// remote kill command
							if (thisMessage.title == "!X") {
								Log('remote kill command received');
								stopPoll();
								return;
							}

							if (thisMessage.date == oldMessage.date) {
								Log('not a new notification');
								// if the message has been displayed for 24 hours
								// gmtDate=new Date(thisMessage.date)
								// if (hoursDisplayed > 24) {
									// Log('24 hour display limit reached');
									// 	clearNotification();
								// }
								return;
							}

							// update oldmessage
							oldMessage.title = thisMessage.title;
							oldMessage.description = thisMessage.description;
							oldMessage.link = thisMessage.link;
							oldMessage.date = thisMessage.date;

							// allclear
							if (thisMessage.description == "ALL CLEAR") {
								Log('all clear received');
								clearNotification();
								return;
							}

							Log('new notification');
							setNotification();

							break;

						default:
							Log('unanticipated status: ' + oHttp.status);
							break;
					}
				}

				//

				function setNotification() {

					changeTextById("alert-title", thisMessage.title);
					changeTextById("alert-message", thisMessage.description);
					changeTextById("alert-date", thisMessage.date);
					//changeTextById("alert-link", thisMessage.link);
					//changeTextById("alert-image", thisMessage.image);

					setDisplay(true, "SPalert");

				}

				function clearNotification() {

					changeTextById("alert-title", "");
					changeTextById("alert-message", "");
					changeTextById("alert-date", "");
					changeTextById("alert-link", "");
					// changeTextById("alert-image", "");

					setDisplay(false, "SPalert");
				}

				function convertOldTime() {
					var _d = new Date(oldMessage.date);
					return _d.getTime()/1000.0;
				}

				// util

				function setDisplay(display, divid)
				{
					var _el = document.getElementById(divid);
					if (_el == null) return;
					_el.style.display = display ? "block" : "none";
				}

				function changeTextById(elm, value) {

					elm = document.getElementById(elm);

					if (!document.all) {
						elm.textContent = value;
					} else {
						elm.innerText = value;
					}
				}

				//

				function getHttp() {
					Log('getting http object...');
					oHttp = false;

					if (window.XMLHttpRequest) { // Mozilla, Safari,...
						oHttp = new XMLHttpRequest();
						if (oHttp.overrideMimeType) oHttp.overrideMimeType('text/xml');
						return true;
					}

					if (window.ActiveXObject) { // IE
						var versions = [
							"Msxml2.XMLHTTP.7.0",
							"Msxml2.XMLHTTP.6.0",
							"Msxml2.XMLHTTP.5.0",
							"Msxml2.XMLHTTP.4.0",
							"MSXML2.XMLHTTP.3.0",
							"MSXML2.XMLHTTP",
							"Microsoft.XMLHTTP"];

						for (var i = 0; i < versions.length; i++) {
							Log('http: trying ' + versions[i] + '...');
							try {
								oHttp = new ActiveXObject(versions[i]);
								break;
							}
							catch (e) { /* next */ }
						}
						if (!oHttp) return true;

					}

					return false;
				}

				/*
				function getParser() {

					Log('attempting to create parser');
					if (window.DOMParser)
					{
						parser=new DOMParser();
						xmlDoc=parser.parseFromString(oHttp.responseXML,"text/xml");
						Log('success - window.DOMParser');
					}
					else // Internet Explorer
					{
						xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
						xmlDoc.async="false";
						xmlDoc.loadXML(oHttp.responseXML);
						Log('success - MSXMLDOM');
					}
				}
			   */
				//

				function safeAddEvent(obj, evType, fn) {
					if (obj.addEventListener) {
						obj.addEventListener(evType, fn, false);
						return true;
					}
					if (obj.attachEvent) {
						var r = obj.attachEvent("on"+evType, fn);
						return r;
					}
					return false;
				}

				//

				function Log(context) {
					var html = getHMS() + " : " + context + "";

            if(window.console) { console.log(html); }

            var _el = document.getElementById("logOutput");
            if (_el == null) return;

            var elem = document.createElement("span");
            if (elem == null) return;

            elem.innerHTML = html;
            _el.appendChild(elem);
            elem.scrollIntoView();
            }

            function getHMS() {
            var d = new Date();
            return pad(d.getHours(), 2) + ":" + pad(d.getMinutes(), 2)+ ":" + pad(d.getSeconds(), 2);
            }

            function pad(n, totalDigits) {
            n = n.toString();
            var pd = '';
            if (totalDigits > n.length) {
            for (i=0; i < (totalDigits-n.length); i++) {
            pd += '0';
            }
            }
            return pd + n.toString();
            }

            function createTimestamp() {
            var _d = new Date();
            return _d.getTime();
            }


            return {
            setDisplay:setDisplay
            }
            // end util

            }());

		

PHP

CSS Sprite Button Generator

This example demonstrates some basic php OOP principles around the concept of a button generator.

The code allows for definition of a button, colors, size, and other properties. An instance of the class will allow the user to generate the image file, the css for rollovers, and the html to add the button to the page.

It's useful for rapidly creating a navigation system with graphics. The graphics can then be imported into photoshop and customized. The math and position for the various states is already handled.

Two functions were used from the php.net website which allow for centering the text on the button.

Source Code


			< ?

			///////////////////////////////////////////////////////////////////////////////

			// button library
			// facility to generate images / css for css sprite buttons with four states
			// normal | hover | active | 'current'
			// fixme: add a disabled state to the button image

			// fixme: try the new css way of making buttons


			///////////////////////////////////////////////////////////////////////////////

			// fixme: palette of 256 colors
			// fixme: 16 windows colors
			// fixme: CGA / EGA palette

			class Color
			{
				public $red;
				public $green;
				public $blue;
				public $alpha;
			}

			///////////////////////////////////////////////////////////////////////////////

			// class cssSpriteButton
			class Button
			{

				public $left = 0;
				public $top = 0;

				public $link = "";

				public $name;
				public $width;
				public $height;

				public $font;
				public $backgroundimage;

				public $background;
				public $linecolor;
				public $textcolor;

				public $activecolor;
				public $hovercolor;
				public $currentcolor;

				public $path_save;

				// icon, iconx, icony

				// textalign

				function __construct($name, $link, $width, $height, $left, $top)
				{
						$this->name = $name;
						$this->link = $link;
						$this->width = $width;
						$this->height = $height;
						$this->left = $left;
						$this->top = $top;
				}

				function html()
				{

					// if disabled
					// if current

					$name = $this->name;
					$lname = strtolower($this->link);

					return '
  • '.$name.'
  • '."\n"; } function selectedhtml() { // if disabled // if current $name = $this->name; $lname = strtolower($this->link); return '
  • '.$name.'
  • '."\n"; } function css() { $name = strtolower($this->name); $left = $this->left; $width = $this->width; $height = $this->height; $top = $this->top; $out .= "#toolbar li.btn-".$name." a { background: url(btn-".$name.".gif); width:".$width."px; height: ".$height."px; }\n"; $out .= "#toolbar li.btn-".$name." a:hover { background: url(btn-".$name.".gif) 0px -".$height."px no-repeat; }\n"; $out .= "#toolbar li.btn-".$name." a:active { background:url(btn-".$name.".gif) 0px -".($height*2)."px no-repeat; }\n"; $out .= "#toolbar li.btn-".$name." a.selected { background: url(btn-".$name.".gif) 0px -".($height*3)."px no-repeat; }\n"; $out .= "#toolbar li.btn-".$name." a.disabled { background: url(btn-".$name.".gif) 0px -".($height*4)."px no-repeat; }\n"; $out .= "#toolbar li.btn-".$name." a.alert { background: url(btn-".$name.".gif) 0px -".($height*5)."px no-repeat; }\n\n"; return $out; } function save() { // fixme: errorproof // fixme: baseimage // fixme: activecolor // hovercolor // currentcolor /* $image = imagecreatetruecolor(192, 36); $trans_color = imagecolorallocate($image, 255, 0, 0); $color = imagecolorallocate($image, 255, 255, 255); imagecolortransparent($image, $trans_color); imagegif($image, "output.gif"); imagedestroy($image); */ $name = $this->name; $width = $this->width; $height = $this->height; // fixme: either transparent background // or png with alpha channel // $my_img = imagecreatetruecolor( $width, ($height * 6) ); $trans_color = imagecolorallocate( $my_img, 255, 0, 255 ); imagecolortransparent ( $my_img , $trans_color ); $background = imagecolorallocate( $my_img, 0, 0, 0 ); $text_color = imagecolorallocate( $my_img, 255, 255, 0 ); $line_color = imagecolorallocate( $my_img, 128, 255, 0 ); $extra_color = imagecolorallocate( $my_img, 128, 128, 128 ); $active_color = imagecolorallocate( $my_img, 64, 0, 0 ); $active_text_color = imagecolorallocate( $my_img, 255,0, 0 ); $disabled_color = imagecolorallocate( $my_img, 64, 64, 64 ); $disabled_text_color = imagecolorallocate( $my_img, 128, 128, 128 ); $alert_color = imagecolorallocate( $my_img, 64, 64, 64 ); $alert_text_color = imagecolorallocate( $my_img, 128, 128, 128 ); $current_color = imagecolorallocate( $my_img, 0, 0, 64 ); $current_text_color = imagecolorallocate( $my_img, 0, 0, 255 ); // fill canvas with transparent imagefilledrectangle ( $my_img , 0 , 0 , $width, $height * 6, $trans_color ); // set the transparency color // create a round rectangle for each button state imagefillroundedrect($my_img,1,2,$width - 2,$height - 2,5,$extra_color); imagefillroundedrect($my_img,1,$height + 2,$width - 2,$height * 2 - 2,5,$line_color); imagefillroundedrect($my_img,1,$height * 2 + 2,$width - 2,$height * 3 - 2,5,$active_color); imagefillroundedrect($my_img,1,$height * 3 + 2,$width - 2,$height * 4 - 2,5,$disabled_color); imagefillroundedrect($my_img,1,$height * 4 + 2,$width - 2,$height * 5 - 2,5,$alert_color); imagefillroundedrect($my_img,1,$height * 5 + 2,$width - 2,$height * 6 - 2,5,$current_color); // draw line //imagesetthickness ( $my_img, 1 ); //imagettftext($image, 10, 0, 10, 23, $color, "impact.ttf", " MENU ITEM"); // //imageline( $my_img, 1, $height, $width, $height, $line_color ); //imageline( $my_img, 1, $height * 2, $width, $height * 2, $line_color ); //imageline( $my_img, 1, $height * 3, $width, $height * 3, $line_color ); //imageline( $my_img, 1, $height * 4, $width, $height * 4, $line_color ); // add text //imagestring( $my_img, 4, 5, 0, $name, $text_color ); //imagestring( $my_img, 4, 5, $height, $name.":hover", $text_color ); //imagestring( $my_img, 4, 5, $height * 2, $name.":active", $text_color ); //imagestring( $my_img, 4, 5, $height * 3, $name.":~current", $text_color ); // add text to each button centerimagestring($my_img, $width, $name, 5, $height / 2, $text_color); centerimagestring($my_img, $width, $name."", 5, $height + $height / 2, $text_color); centerimagestring($my_img, $width, $name."", 5, $height * 2 + $height / 2, $active_text_color); centerimagestring($my_img, $width, $name."", 5, $height * 3 + $height / 2, $disabled_text_color); centerimagestring($my_img, $width, $name."", 5, $height * 4 + $height / 2, $alert_text_color); centerimagestring($my_img, $width, $name."", 5, $height * 5 + $height / 2, $curreny_text_color); // save imagegif( $my_img, $this->path_save."btn-".strtolower($name).".gif" ); // cleanup imagecolordeallocate( $my_img, $current_text_color ); imagecolordeallocate( $my_img, $current_color ); imagecolordeallocate( $my_img, $alert_text_color ); imagecolordeallocate( $my_img, $alert_color ); imagecolordeallocate( $my_img, $disabled_text_color ); imagecolordeallocate( $my_img, $disabled_color ); imagecolordeallocate( $my_img, $active_text_color ); imagecolordeallocate( $my_img, $active_color ); imagecolordeallocate( $my_img, $extra_color ); imagecolordeallocate( $my_img, $line_color ); imagecolordeallocate( $my_img, $text_color ); imagecolordeallocate( $my_img, $background ); imagecolordeallocate( $my_img, $trans_color ); // imagedestroy( $my_img ); return true; } } /////////////////////////////////////////////////////////////////////////////// define("ALIGN_LEFT", "left"); define("ALIGN_CENTER", "center"); define("ALIGN_RIGHT", "right"); define("VALIGN_TOP", "top"); define("VALIGN_MIDDLE", "middle"); define("VALIGN_BOTTOM", "bottom"); /////////////////////////////////////////////////////////////////////////////// function centerimagestring($image, $image_width, $string, $font_size, $y, $color) { $text_width = imagefontwidth($font_size)*strlen($string); $center = ceil($image_width / 2); $x = $center - (ceil($text_width/2)); imagestring($image, $font_size, $x, $y, $string, $color); } function imagestringbox(&$image, $font, $left, $top, $right, $bottom, $align, $valign, $leading, $text, $color) { // Get size of box $height = $bottom - $top; $width = $right - $left; // Break the text into lines, and into an array $lines = wordwrap($text, floor($width / imagefontwidth($font)), "\n", true); $lines = explode("\n", $lines); // Other important numbers $line_height = imagefontheight($font) + $leading; $line_count = floor($height / $line_height); $line_count = ($line_count > count($lines)) ? (count($lines)) : ($line_count); // Loop through lines for ($i = 0; $i < $line_count; $i++) { // Vertical Align switch($valign) { case VALIGN_TOP: // Top $y = $top + ($i * $line_height); break; case VALIGN_MIDDLE: // Middle $y = $top + (($height - ($line_count * $line_height)) / 2) + ($i * $line_height); break; case VALIGN_BOTTOM: // Bottom $y = ($top + $height) - ($line_count * $line_height) + ($i * $line_height); break; default: return false; } // Horizontal Align $line_width = strlen($lines[$i]) * imagefontwidth($font); switch($align) { case ALIGN_LEFT: // Left $x = $left; break; case ALIGN_CENTER: // Center $x = $left + (($width - $line_width) / 2); break; case ALIGN_RIGHT: // Right $x = $left + ($width - $line_width); break; default: return false; } // Draw imagestring($image, $font, $x, $y, $lines[$i], $color); } return true; } /////////////////////////////////////////////////////////////////////////////// function imagefillroundedrect($im,$x,$y,$cx,$cy,$rad,$col) { // Draw the middle cross shape of the rectangle imagefilledrectangle($im,$x,$y+$rad,$cx,$cy-$rad,$col); imagefilledrectangle($im,$x+$rad,$y,$cx-$rad,$cy,$col); $dia = $rad*2; // Now fill in the rounded corners imagefilledellipse($im, $x+$rad, $y+$rad, $rad*2, $dia, $col); imagefilledellipse($im, $x+$rad, $cy-$rad, $rad*2, $dia, $col); imagefilledellipse($im, $cx-$rad, $cy-$rad, $rad*2, $dia, $col); imagefilledellipse($im, $cx-$rad, $y+$rad, $rad*2, $dia, $col); } /////////////////////////////////////////////////////////////////////////////// // create the banner // function saveheader($path_save, $name, $tagline) { //$my_img = imagecreate( 800, 200 ); //imagepng( $my_img, "header.png" ); // fixme: errorproof // fixme: baseimage // taglinecolor //$name = "Rob Lindman"; $width = 800; $height = 200; $my_img = imagecreate( $width, $height ); $background = imagecolorallocate( $my_img, 0, 0, 0 ); $text_color = imagecolorallocate( $my_img, 255, 255, 0 ); $line_color = imagecolorallocate( $my_img, 128, 255, 0 ); // draw line imagesetthickness ( $my_img, 15 ); imageline( $my_img, 1, $height - 60, $width, $height - 60, $line_color ); // add text //imagestring( $my_img, 4, 5, 100, $name, $text_color ); $text_width = imagefontwidth(5)*strlen($name); $center = ceil($width / 2); $x = $center - (ceil($text_width/2)); imagestring($my_img, 5, $x, 0, $name, $text_color); //$nameb = "Software Developer"; $text_width = imagefontwidth(5)*strlen($tagline); $center = ceil($width / 2); $x = $center - (ceil($text_width/2)); imagestring($my_img, 5, $x, 25, $tagline, $text_color); // save imagepng( $my_img, $path_save."header.png" ); // cleanup imagecolordeallocate( $my_img, $line_color ); imagecolordeallocate( $my_img, $text_color ); imagecolordeallocate( $my_img, $background ); imagedestroy( $my_img ); return true; } ? >

    C#.NET

    These files constitute a small system which can be used to construct a DICT client. DICT is a little known protocol which serves definitions over the internet.

    Note: certain lines may or may not be removed from these files to preserve the integrity of the 'originals'. If you are a serious employer and require the 'originals' or latest versions, we can discuss that.

    • Basic demonstration of inheritance, class handling, and event handling
    • socket class demonstrates proper handling of internal and external properties
    • highly efficient asynchronous socket class is very reusable for many clear text protocols
    • This is a unique demonstration, there are no other C# DICT clients.
    • I plan shortly to update this example with some more advanced parsing. It is largely to demonstrate the socket client class and general coding principles.

    Source Code

    Dict Client Class
    Download Source Code
    Socket Client Class
    Download Source Code

    SQL / Transact SQL

    Here are some samples of embedded SQL code from PHP.

    create table

    
    CREATE TABLE IF NOT EXISTS `main` (
    `id` int(6) NOT NULL auto_increment,
    `first` varchar(255) NOT NULL default '',
    `last` varchar(255) NOT NULL default '',
    `message` varchar(255) NOT NULL default '',
    `joy` varchar(255) NOT NULL default '',
    `active` tinyint(1) NOT NULL default '1',
    `cdate` timestamp NOT NULL default CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`),
    UNIQUE KEY (`id`)
    ) ENGINE=MyISAM AUTO_INCREMENT=1 ;
    

    select

    
    $query = "SELECT * FROM ".$this->table." WHERE ".$this->identityfield." = '".$this->identity."' ";
    

    insert

    
    $query = "INSERT INTO ".$this->table." (first, last, message, joy) VALUES ('".$this->first."', '".$this->last."', '".$this->message."', '".$this->joy."')";
    

    update

    
    					$query = "UPDATE ".$this->table." SET first='".$this->first."', last='".$this->last."', message='".$this->message."', joy='".$this->joy."' WHERE ".$this->identity." ='.$this->identity.'";
    
    		

    delete

    
    					$query = "DELETE FROM ".$this->table." WHERE ".$this->identityfield." = ".$this->identity;
    
    		

    Flash Gallery

    Recently, I was trained in the use of Adobe Flash CS3 as well as ActionScript 3. I am in the process of creating some examples to demonstrate my skills with this platform. I am doing this quickly to demonstrate general knowledge of Flash to prospective employers, so I will start with some basic examples, and gradually work up to more sophisticated examples as time permits.

    Banner Example

    A rudimentary example demonstrating frame based animation and motion tweening.


    Combined SWF Library Example

    I combined two SWFs and imported them into the library to produce this example. As the remainder of this website demonstrates my capabilities with graphics, I didn't expend a great deal of time making it look perfect.

    jQuery Samples

    This section contains samples which implement jQuery for various tasks.

     

    Visibility Example

    Simple example using jQuery's animated 'show' and 'hide' functionality on a DOM element.


     

    CSS Sprites Navigation Example

    Demonstrates the use of jQuery to create a CSS-driven navigation with the four basic button states. Uses CSS Sprites, which leverage a single graphic for the entire menu - reducing bandwidth usage and ensuring proper loading of the menu.