Author: Justin

Simple Class Declaration and Initialization with PHP5

If you’re used to classes with C#, C++, and Java, then you’re used to classes in PHP as well. If you’re brand new to classes, I suggest you read up on the definition and uses of them before trying to implement them via this tiny tutorial.

To begin, let’s create a simple class that will store information about a logged in user from a session. This class should hold the user’s username, first name, and last name to identify who it is on subsequent pages and requests. Begin by naming this class as “UserPassport” and adding the three previously described properties. They should not have default values because the class does not make sense without properties assigned during construction.

class UserPassport
	public $userName;
	public $firstName;
	public $lastName;

Expanding on this class, we need to add a constructor and a method to use these properties in a semi-meaningful manner.

class UserPassport
	public $userName;
	public $firstName;
	public $lastName;

    public function UserPassport($uName, $fName, $lName)
		$this-userName = $uName;
		$this-firstName = $fName;
		$this-lastName = $lName;

    public function displayInfo()
		$userInfo = array($this-userName, $this-firstName, $this-lastName);
		echo implode(', ', $userInfo);

There’s nothing crazy going on in the constructor. It’s a simple matter of assigning the properties values from whatever was passed in at construction. To display the information, a displayInfo method is created that places the three values in an array and splices them together separated by a comma and a single space. This value is then echoed to the output stream.

Now, this class is pretty useless if nothing is instantiating instances of it. Below is an example of how to instantiate and display the contents of our class. I used the xhtml 1.1 from The Web Standards Project to define a blank page.

function __autoload($class_name) {
	require_once $class_name . '.php';
?<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
""<html xmlns=""<head<titleDisplay User Information</title</head<body<?php
	$userPassport = new UserPassport('jsmith', 'John', 'Smith');

The __autoload method is used to allow auto instantiation of classes without requiring an include statement to the .php file containing the definition. This is often useful if you are like me in the sense that you create one class per file. Without this __autoload method, we would need to have many include statements for each class that we are including. In this specific example, it is unnecessary, but still useful to know for the future.

A new userPassport object is created with initialize values of jsmith for username, John for first name, and Smith for last name. In a real world application, these values would be populated from a database based on login and stored for later use. Calling the displayInfo method on this object will result in the initialized values to be echoed between the HTML body tags as expected.

The resulting output:

jsmith, John, Smith


Read more

Solving a Simple ODE with Simulink

If you have just started learning Simulink, one of the easiest tasks is solving a simple ordinary differential equation. In fact, most of the beginning guides you will find through web searches will probably be similar to the example I am going to provide. Let’s start by assuming you have the following common spring-damper system. For reference, m is mass, c is the damper coefficient, k is the spring coefficient, x is the position, x-prime is the velocity, x-double-prime is the acceleration, and f(t) is a step-input function with a magnitude of 3.


We begin first by solving for the second derivative of x. In this case, it ends up solving to:


Now, it is time to place this into Simulink using the following blocks:

  • 2 integrator blocks
  • 3 gain blocks
  • 1 sum block
  • 1 step input block
  • 1 scope output block

Step 1) Connect two integrator blocks together to simulate a double integration as seen below:

Step 2) Add the appropriate gain blocks to simulate c*x’ and kx.

Step 3) Add the sum block to simulate f(t) – cx’ – kx.

Step 4) Add the gain block after the summation to simulate the multiplication of (1 / m) and the step input function as the third input to the sum block added in Step 3. Make sure the step input function has the properties of Step Time = 0, Initial Value = 0, Final Value = 3.

Step 5) Add the scope block for output after the second integration to view the plotted contents of the numerical solution.

Using the following values for variables and initial conditions, you should see the plotted results as follows:
x(0)=0, x’(0)=0, x”(0)=0, m=0.25, c=0.5, k=1
resultsRead more

Generating Pseudo Random Numbers in MATLAB

I wrote the code found in this post in the Student Version of MATLAB R2009a ( on Windows Vista SP2.

function U = js_randv(i, x)
%js_randv Pseudo Random Number Vector Generator
% Returns a pseudo random number vector
% according to congruential random number generator
%   i = length of vector
%   x = seed value of sequence
%   U = vector of Xi+1 = (a * Xi) mod m

isFirst = 0;

a = 16807;          % 7^5 predetermined multiplicative value
m = 2147483647;     % 2^31-1 predetermined prime number
r = 2836;           % m div a
q = 127773;         % m mod a
T = zeros(1, i);    % holds seed values
U = zeros(1, i);    % holds returned uniform random numbers in (0,1)

% loop through all indices of vector
for j=1:i
    % if this is the first value, use seed
    if isFirst == 0
        seed = (a * mod(x, q)) - (r * (x / q));
        T(1, j) = seed;
        isFirst = 1;
    % if this is not the first value, use current index
        previousValue = T(1, j-1);
        seed = (a * mod(previousValue, q)) - (r * (previousValue / q));
        T(1, j) = seed;

	U(1, j) = seed / m;

This function will return a vector of size i containing randomly generated numbers uniformly distributed between 0 and 1. It’s not perfect, but it got the job done. I’ll get around to explaining it more beyond the meager comments another time.

Generating Random Numbers
Linear congruential generatorRead more

Windows Vista – Moving C:Users to Another Location

Moving your personal documents to a location other than the system partition is a good idea for several reasons. Namely, if your system crashes, you can format and reinstall Windows without affecting your personal files or requiring you to move them to another location. Of course, this does not work if the entire drive crashes and takes your personal files with it!

Follow these steps (D: is the name of my location, change it to match yours):

  1. Backup your C:Users folder to an external location
  2. Boot from Windows Vista install DVD
  3. Click “Repair” from main install screen
  4. Click Command Prompt
      • robocopy C:Users D:Users /mir /xj
      • rmdir /S /Q C:Users
      • rmdir “C:Documents and Settings”
      • mklink /J C:Users D:Users
      • mklink /J “C:Documents and Settings” D:Users
      1. Reboot

      You’ll notice that C:Users now has an arrow on its icon designating that it is a link to another location. Remember to set proper permissions and remove read-only status from the new D:Users so all applications work properly!… Read more

      Creating a Professional ToolStrip in Windows Forms Part 2

      In my previous post, I explained how to create the basic UI elements of a simple Windows Forms application with a nice looking vertical ToolStrip menu to host buttons and labels without ever leaving the Designer. In this post, I’ll explain how to wire up some events, load in some UserControl objects, and add a custom rendering method to style our MouseClick events on the ToolStrip buttons. We’ll begin by opening the project from our previous post. (seen here)


      • Microsoft Visual Studio 2008 (or 2005, but I wrote this using 2008)
      • .NET Framework 3.5 (or 2.0, but I wrote this using 3.5)
      • Basic x,y coordinate knowledge to draw and position rectangles
      • Intermediate knowledge of C# and Windows Forms
        • Inheritance and overrides
        • Event handling

      Step 1 – Create a Custom Rendering Class

      • Right click on the Project in the Solution Explorer, Add –> New Item… –> Class (.cs).
      • Name this class customRenderer.cs and click OK.

      This class is going to inherit from ToolStripProfessionalRenderer so that we can override some of the rendering methods and make them do whatever we want. In this case, however, we will only be overriding the OnRenderButtonBackground method.

      public class customRenderer : ToolStripProfessionalRenderer
          protected override void OnRenderButtonBackground(ToolStripItemRenderEventArgs e)

      By overriding this method, we can change the behavior of how backgrounds are rendered. Some conditions will need to be applied in order to enforce that custom rendering only occurs on ToolStripButton objects and only when the objects are in a Checked state. Read through the comments in the next code block in order to understand some of the sections.

      public class customRenderer : ToolStripProfessionalRenderer
          protected override void OnRenderButtonBackground(ToolStripItemRenderEventArgs e)
              // check if the object being rendered is actually a ToolStripButton
              if (e.Item is ToolStripButton)
                  ToolStripButton button = e.Item as ToolStripButton;
                  // only render checked items differently
                  if (button.Checked)
                      // fill the entire button with a color (will be used as a border)
                      int buttonHeight = button.Size.Height;
                      int buttonWidth = button.Size.Width;
                      Rectangle buttonFill = new Rectangle(Point.Empty, new Size(buttonWidth, buttonHeight));
                      e.Graphics.FillRectangle(Brushes.SteelBlue, buttonFill);
                      // fill the entire button offset by 1,1 and height/width subtracted by 2 used as the fill color
                      int backgroundHeight = button.Size.Height - 2;
                      int backgroundWidth = button.Size.Width - 2;
                      Rectangle background = new Rectangle(1, 1, backgroundWidth, backgroundHeight);
                      e.Graphics.FillRectangle(Brushes.LightSkyBlue, background);
                  // if this button is not checked, use the normal render event
              // if this object is not a ToolStripButton, use the normal render event

      Take a few minutes to read through the above block of code in order to fully understand what’s happening. Follow the bullets below for an overview:

      • When Windows renders the button background on a ToolStrip, this overridden method will be called instead.
      • Only use our custom render code if the item is a ToolStripButton object.
      • Only use our custom render code if the ToolStripButton has its Checked property set to True.
      • Now, two different rectangles are going to be created and filled in order to achieve a 1 pixel border color that differs from the body color of the rendered button.
      Read more

      Creating a Professional ToolStrip in Windows Forms

      Ever wanted to create a professional looking menu in your Windows Forms applications complete with big buttons, nice mouse over effects, and images? Well, look no further. In this post, I’ll show you how to implement a graphical ToolStrip menu to navigate through a Single Document Interface (SDI). You’ll notice that the finished interface is rather similar to Spybot – Search and Destroy. Keep in mind that the following example is rather simple and leaves a lot of room for expansion.


      • Microsoft Visual Studio 2008 (or 2005, but I wrote this using 2008)
      • .NET Framework 3.5 (or 2.0, but I wrote this using 3.5)
      • Beginner’s Knowledge Windows Forms

      Step 1 – Create the Form Shell to Host the Menu

      • Create a new Windows Forms Application Project.
      • Select Form1 and adjust it’s size in the Properties Window to 964,600 (the exact size isn’t important, but you want to leave room for other controls once the menu is operational).

      Step 2 – Add the Menus

      • From the Toolbox:
        • Drag in a MenuStrip and snap it to the top of Form1 by either dragging it until the blue line snaps to the top of the form, or drop it in Form1 and set the MenuStrip object’s Dock property to Top.
        • Drag in a TableLayoutPanel to the center of the form.
          • From the submenu that pops up when you drop in the TableLayoutPanel, click “Remove Last Row.”
          • Set this new Container’s Dock property to Fill.
          • From the Toolbox, drag in a ToolStrip and drop it into the left column of the new TableLayoutPanel.
          • Click the “…” button in the Property Window for this new control’s Columns property.
          • Set Column1 width to absolute 115px and Column2 width to relative 100%.
        • Drag a ToolStrip into the left column (Column1).
          • Set its Dock property to Fill.
          • Set its LayoutStyle property to VerticalStackWithOverflow. This will cause contents to stack top to bottom.
          • Set its GripStyle property to Hidden. This is only a matter of preference.
          • Set its Padding property to 5,5,5,5. This will give space on all sides for its contents.
          • Set its ImageScalingSize property to 35, 35. This will force images on Buttons to scale to 35px by 35px.

      Step 3 – Add Content to the Menus

      • Using the “Add New Item” drop down in the ToolStrip:
        • Add a Label (menu section title).
        • Add two Buttons (menu section content).
        • Add a Label (menu section title).
        • Add three Buttons (menu section content).
      • While holding control, select each Button on the ToolStrip:
        • Set their DisplayStyle property to ImageAndText. This will cause a caption to be added to the Button in addition to an image.
        • Set their TextImageRelation property to ImageAboveText. This will cause the caption to be below the Button’s image.
        • Set their CheckOnClick property to True. This will cause the button to display as pressed or checked when clicked a single time. We will make the check state mutually exclusive for all buttons on the ToolStrip so that only one button can be checked at any given time to enforce SDI behavior.
      Read more