Life as Clay

Posts Tagged ‘tutorial

Using Colorbox with Rails 3.1

with 2 comments

I’m in the midst of creating a mini-Facebook like Rails app that I can use to track events in my daughter’s life. Part of that includes the ability to attach photos to events. I wanted to use a friendly modal popup for displaying larger versions of photos, so I elected to go with ColorBox. It’s a jQuery plugin that is dead simple to use, especially on static pages.

For the “timeline” page, a dynamic page, I never know whether there will be photos to display and if there are, how they are grouped. The idea is that photos that are attached to the same event should all be part of one gallery.

Here’s what I did…

Anything that can end up on the timeline is a “mark” in my app. I use a partial when iterating through the marks to display photos that may be associated with the mark. Here is that partial:

<% if mark.images.count > 0 %>
	<div class="mark_images">
		<% for image in mark.images %>
				<a href="<%= image.pic(:large) %>" class="gallery_<%= mark.id %>" title="<%= image.caption %>"><%= image_tag(image.pic(:tiny), :title => image.caption, :class => "mark_image") %></a>
		<% end%>
	</div>
<% end %>

As you can see, I’m using thumbnail images as links. The images, by the way, are attached using the Paperclip gem from thoughtbot. The code above sets up the HTML that ColorBox needs in order to display the modal.

The rest of the work comes in javascript. I elected to put the ColorBox javascript at the end of my application.js file. It looks like this:

$(document).ready(function() {
	galleries = [];
	$('a[class^="gallery_"]').each( function() {
		if ($.inArray($(this).attr("class"), galleries) == -1) {
			$(this).colorbox({
				rel: $(this).attr("class"),
				maxWidth: "95%",
				maxHeight: "95%"
			});
			galleries.push($(this).attr("class"));
		}
	});
});

Here I create an empty array called galleries. I then find all link elements on the page that have a class that begins with “gallery_“. I iterate on each of them. If the class of the element is not in the galleries array, then I set up ColorBox for that class (gallery) and I add the class name to the galleries array so that I know not to set it up again.

Finally, I use the class of the gallery to relate the images that share the same class together, so that I get the navigational buttons on the modal viewbox.

To make this all work, you have to drop the ColorBox .js file into your assets/javascripts directory and you need to include both the .css file that you prefer (from the ColorBox downloadable examples) and the images that accompany it. I chose to use example 3. I had to modify the css image paths so that it would locate the ColorBox images in my assets/images directory. I elected to rename the enclosing folder to colorbox_images. The css file I ended up with looks like this:

/*
    ColorBox Core Style:
    The following CSS is consistent between example themes and should not be altered.
*/
#colorbox, #cboxOverlay, #cboxWrapper{position:absolute; top:0; left:0; z-index:9999; overflow:hidden;}
#cboxOverlay{position:fixed; width:100%; height:100%;}
#cboxMiddleLeft, #cboxBottomLeft{clear:left;}
#cboxContent{position:relative;}
#cboxLoadedContent{overflow:auto;}
#cboxTitle{margin:0;}
#cboxLoadingOverlay, #cboxLoadingGraphic{position:absolute; top:0; left:0; width:100%;}
#cboxPrevious, #cboxNext, #cboxClose, #cboxSlideshow{cursor:pointer;}
.cboxPhoto{float:left; margin:auto; border:0; display:block;}
.cboxIframe{width:100%; height:100%; display:block; border:0;}

/*
    User Style:
    Change the following styles to modify the appearance of ColorBox.  They are
    ordered & tabbed in a way that represents the nesting of the generated HTML.
*/
#cboxOverlay{background:#000;}
#colorbox{}
    #cboxContent{margin-top:20px;margin-bottom:20px}
        .cboxIframe{background:#fff;}
        #cboxError{padding:50px; border:1px solid #ccc;}
        #cboxLoadedContent{border:5px solid #000; background:#fff;}
        #cboxTitle{position:absolute; bottom:-15px; left:0; color:#ccc;}
        #cboxCurrent{position:absolute; top:-20px; right:0px; color:#ccc;}
        #cboxSlideshow{position:absolute; top:-20px; right:90px; color:#fff;}
        #cboxPrevious{position:absolute; top:50%; left:5px; margin-top:-32px; background:url(/assets/colorbox_images/controls.png) no-repeat top left; width:28px; height:65px; text-indent:-9999px;}
        #cboxPrevious:hover{background-position:bottom left;}
        #cboxNext{position:absolute; top:50%; right:5px; margin-top:-32px; background:url(/assets/colorbox_images/controls.png) no-repeat top right; width:28px; height:65px; text-indent:-9999px;}
        #cboxNext:hover{background-position:bottom right;}
        #cboxLoadingOverlay{background:#000;}
        #cboxLoadingGraphic{background:url(/assets/colorbox_images/loading.gif) no-repeat center center;}
        #cboxClose{position:absolute; top:5px; right:5px; display:block; background:url(/assets/colorbox_images/controls.png) no-repeat top center; width:38px; height:19px; text-indent:-9999px;}
        #cboxClose:hover{background-position:bottom center;}

I also chose to move the title to the bottom of the image because that way, it doesn’t bump up against the image count when viewed on a mobile device. That required setting a bottom margin for #cboxContent and changing this line: #cboxTitle{position:absolute; bottom:-15px; left:0; color:#ccc;}.

There are a variety of other options that can be used with the javascript call to alter the modal dialogue. It’s worth taking a look at the ColorBox page for some examples.

Overall, I’m really happy with this solution and probably will use it again in the future. If you’re interested in the app that I’m developing, you can find it on github, called Blytheline. It’s an early work in progress, so it’s a bit rough around the edges!

Written by Clay

November 29, 2011 at 12:53

Connecting NSOutlineView to Core Data in 10.6 Part 1: Ordered Trees

NOTE: This tutorial is now outdated. I’m leaving it here for posterity, but please know that it may not work.

There are aspects to Cocoa that I find extremely obtuse and difficult to implement. I’m relatively new both to programming and Cocoa, and I suspect that others in the same boat also are frustrated by these steps. The single most frustrating simple thing that I have come across is implementing an NSOutlineView that connects to a Core Data model. There are several ways to approach this problem; primarily with or without Cocoa Bindings and with or without sorting.

There is a good, but outdated tutorial on how to make this work at this link: http://allusions.sourceforge.net/articles/treeDragPart1.php

The primary problem with the tutorials is that it requires the use of private Apple methods, which means that anything you build with it will not be accepted into the Mac App Store. This tutorial draws very heavily on that tutorial, with updated screenshots and code that does not use private APIs. The code also is difficult to read on that page, so it’s updated here in an easier-to-read format. Oh, and one more thing: the example on that page uses a feature of Interface Builder that no longer exists – subclassing within IB.

This tutorial is done with Xcode 3.2.5 on OS X 10.6.6.

The tutorial continues after the break…

Read the rest of this entry »

Written by Clay

February 13, 2011 at 09:31

Learning R: Using Sweave on OS X 10.6 and fix the Sweave.sty problem

with 9 comments

I’m trying to teach myself R for a work-related project. The documentation is absolutely terrible for beginners, which is a shame, since the language is easy. Stuff that should take 1 minute takes 4 hours because there is a paucity of good tutorials on the Internet.

R comes with Sweave preinstalled. The concept is pretty cool. If you want to lay out your journal article or publication using LaTeX, then Sweave allows you to imbed the R code in the LaTeX document. It goes like this:

  1. You have two things: your source data file and your R code.
  2. You put the R code into a file that Sweave will process. That file can have several different extensions, like .Snw or .Rnw, for example. The Sweave file also includes your LaTeX code for formatting the final document.
  3. From within the R environment (this also can be done from the command line), you use the function Sweave() to process your R code and generate the .tex file. It automatically generates intermediate .eps and .pdf files of the components needed for the LaTeX output.
  4. You run pdflatex against your .tex file and end up with a pretty .pdf file, ready for publication.

This is a cool thing because it means that you can send the .Snw (Sweave) file to anybody and they automatically can reproduce the results with their own installation of R. As we know, reproducibility is a big deal for scientific studies.

There are a three major problems for the beginner:

  • R code is unnecessarily cryptic
  • The documentation is meant for people familiar with R and it’s TERRIBLE for beginners.
  • LaTeX is not installed by default on Macs.
  • Sweave runs fine out of the box, but LaTeX won’t be able to process the .tex files it generates because it will not be able to locate the Sweave.sty (style) file.

If you are a Mac user, this is what you have to do to use this system.

  1. Download and install LaTeX.
  2. Download and install R.
  3. Reboot. Probably not necessary, but I’d do it anyhow.
  4. Open Terminal.
  5. Type: mkdir -p ~/Library/texmf/tex/latex
  6. Type: cd ~/Library/texmf/tex/latex
  7. Type: ln -s /Library/Frameworks/R.framework/Resources/share/texmf Sweave
    What this does is create a symbolic link to Sweave that LaTeX can find so that you don’t get the error message from LaTeX about not finding Sweave.sty.

That’s it. You’re ready to use Sweave. Here’s how you can test it. This is what I did, just so that I could find the files more easily. You can put your working directory anywhere you want.

  1. Create a folder on the Desktop called: routput
  2. Launch R.
  3. Enter the following code:
# Clear variables from your environment, in case you were doing other work.
rm(list=ls())

# Set the working directory to the folder you created on the Desktop - replace 'clay' with your username
setwd("/Users/clay/Desktop/routput")

# Load the Sweave test file into the testfile variable
testfile <- system.file("Sweave", "Sweave-test-1.Rnw", package = "utils")

# Run Sweave against the test file
Sweave(testfile)

Now, take a look in the routput folder on your Desktop and you will see the files that Sweave generated. You need to run pdflatex to convert the .tex file to a .pdf file.

  1. Open Terminal.app
  2. Type: cd ~/Desktop/routput
  3. Type: pdflatex Sweave-test-1.tex
  4. Go look in the routput folder on the desktop to find your completed document

Next steps: locate the Sweave-test-1.Rnw file in your R structure and use it as a reference for doing your own Sweave work. The documentation on the Sweave homepage is pretty good.

I hope this helps you get started with Sweave!

Written by Clay

March 21, 2010 at 22:19

Posted in Code, R

Tagged with , , ,

Learning Actionscript 3 with Adobe Flash Builder / Flex Builder

with one comment

I tried to learn Flash several times over the past few years but I always gave up because the Adobe Flash CS3 interface is littered with a bunch of stuff that distracts me. As a brief aside, I decided that I wanted to learn Actionscript several years ago, when Jenova Chen posted his thesis game, Flow, to the web. This game later became Flow on the PS3. I was wowed with the graphics and overall feeling of the game, so I contacted him to ask how he made it. His response: it was procedurally generated in Flash and programmed with Actionscript. I bought Flash, got distracted to 100 other things, tried to learn Actionscript several times, and never made any progress.

The good news is that there’s a far better way to work on Actionscript: get yourself a copy of Adobe Flex Builder, which soon will be renamed to Adobe Flash Builder to distinguish it from the free Flex SDK.  The cool thing is that you can get a copy of it for free if you are a student or if you are unemployed by the current recession. Just visit this link. You also can download a trial version through Adobe’s website.

I mentioned in a previous post that setting up and understanding IDEs is difficult. Flex Builder / Flash Builder is simpler than most. This tutorial is meant to show you what to do after installing the application.

  1. Download it from Adobe or get the free student edition. You also can get the Flash Builder 4 Beta 2 trial for 60 days.
  2. Install it.
  3. Now, remember… this brief tutorial is geared towards learning Actionscript, NOT Flex… I can’t help with that.
  4. Launch the software.
  5. Select File > New > Actionscript Project
  6. Name the project something that has two words, like “Arrow Field” (the example later) and click ok.
  7. You’re now looking at the main class for the project. This is the code that will run automatically when you run something that you build in Flash Builder / Flex Builder. It looks like this:
package
{
	import flash.display.Sprite;

	public class main extends Sprite
	{
		public function main()
		{

		}
	}
}

To get started, I’m going to give you some instructions and code so that you can get a small project up and running. This is partially derived from the Actionscript 3.0 Animation book by Keith Peters. It’s a good book.

  1. In the left hand pane you’ll see a hierarchical list of the files in the project you just created. Right-click on the parent Folder and select Properties.
  2. Click where it says “Actionscript Compiler”
  3. Enter this is the “Additional Compiler Arguments” field: -default-size 800 600 -default-frame-rate 30 -default-background-color 0xffffff
  4. Hit ok to exit the dialog box.
  5. If you named your project something that was one word, the names of the functions in the primary .as file will be that word. If you named the project with two words, the primary .as file should be called main.as. Paste this code into main.as:
package
{
	import flash.display.Sprite;
	import flash.events.Event;

	public class main extends Sprite
	{
		private var arrowArray:Array = new Array();

		public function main()
		{
			init();
		}

		private function init():void
		{
			// This creates the arrows; parameters are (# across, # down)
			createArrows(20,20);

			// This makes the arrows move when the mouse is over the movie
			addEventListener(Event.ENTER_FRAME, onEnterFrame);
		}

		private function createArrows(xnum:Number, ynum:Number):void
		{
			// Create an array of arrows
			var totalArrows:Number = xnum * ynum;
			for (var i:Number = 0; i <= totalArrows; i++)
			{
				var arrow:Arrow = new Arrow();
				arrowArray.push(arrow);
			}

			// Call the function to draw the arrows here
			drawArrows(arrowArray, xnum, ynum);
		}

		private function drawArrows(drawArray:Array, xnum:Number, ynum:Number):void
		{
			// Pass an array to this to draw the arrows in the array
			var startxpos:Number = 25;
			var startypos:Number = 25;

			var currentxpos:Number = startxpos;
			var currentypos:Number = startypos;

			var xshift:Number = (stage.stageWidth - 25) / xnum;
			var yshift:Number = (stage.stageHeight - 25) / ynum;

			var xcount:Number = 0;
			var ycount:Number = 0;

			// Iterate through each arrow in the array
			for (var i:Number = 0; i < drawArray.length - 1; i++)
			{
				var current:Arrow = drawArray[i];
				addChild(current);

				// set the x value
				if (xcount < xnum)
				{
					// Place it at the current x and y position
					current.x = currentxpos;
					current.y = currentypos;

					// Increment the x position
					currentxpos = currentxpos + xshift;

					// Increment the counter so we know how many we have placed on the x
					xcount +=1;
				} else {
					// Set the x back to 0 because we are starting a new row
					xcount = 0;

					// Set the x position back to the starting position
					currentxpos = startxpos;

					// Increment to the new row on the y
					currentypos = currentypos + yshift;

					// Place the arrow
					current.x = currentxpos;
					current.y = currentypos;

					// Increment the x position for the next one
					currentxpos = currentxpos + xshift;

					// Increment the number across the x
					xcount +=1;
				}

				// This code just changes the arrow size, based on how many there are
				if (xnum == ynum)
				{
					current.scaleX = 1/xnum;
					current.scaleY = 1/xnum;
				} else if (xnum < ynum) {
					current.scaleX = 1/ynum;
					current.scaleY = 1/ynum;
				} else {
					current.scaleX = 1/xnum;
					current.scaleY = 1/xnum;
				}
			}
		}

		public function onEnterFrame(event:Event):void
		{
			// this loops goes through each arrow in the array
			for (var i:Number = 0; i < arrowArray.length - 1; i++)
			{
				// Get an arrow from the array
				var current:Arrow = arrowArray[i];

				// Determine the distance between the mouse and the arrow
				var dx:Number = mouseX - current.x;
				var dy:Number = mouseY - current.y;

				// Use the distances to calculate an angle
				var radians:Number = Math.atan2(dy, dx);

				// Use the angle to set the rotation of the arrow
				current.rotation = radians * 180 / Math.PI;

			}
		}
	}
}
  1. Now you’ll create a class file to hold the code for the simple class. Objects created look like simple arrows. The code you just pasted in will make them follow the mouse around. Go to File > New > Actionscript Class.
  2. Name it Arrow. Click ok and ignore the warnings. The Package Explorer pane on the left now will show a file called Arrow.as. It will open automatically, too.
  3. Click Arrow.as to get into the class file. Paste in this code:
package
{
	import flash.display.Sprite;

	public class Arrow extends Sprite
	{
		public function Arrow()
		{
			init();
		}
		public function init():void {
			graphics.lineStyle(4, 0, 1);
			graphics.moveTo(0, 0);
			graphics.lineTo(-100, 100);
			graphics.moveTo(0, 0);
			graphics.lineTo(-100, -100);
		}
	}
}
  1. Now click the “Run” button on the toolbar at the top or select “Run main” from the Run menu. The field of arrows should open in the browser.
  2. Notice the comments in the code – tweaking some of the numbers and/or variables might help you understand what’s going on.  It’s pretty simple code, but has a few twists thrown in so that you can see a few techniques for making things happen.

One thing that you will notice is that the behavior is generated by an array or Arrow objects. An array is created with the total number of arrows that you specify. They are positioned by iterating through the array. Their rotation is set by a separate iteration through the array.

I hope that this helped get you started! Good luck!

Written by Clay

January 22, 2010 at 21:55

Learn to program: tips for the very beginners and things that I wish somebody had explained to me

with one comment

Learning to program is a frustrating and fun process. I think the frustration comes from the fact that the concepts are not particularly difficult or tricky, but it is hard to express them as a beginner. It is akin to trying to learn basic philosophy in a foreign language that you do not speak. There comes a point, however, when the concepts click, and all that remains is to learn the language. The good news is that many programming languages are similar. Learn one and you can hop to another with ease. Mastering programming, on the other hand, will take the rest of your life.

You probably want to learn to program if you are reading this. You may not have chosen a language and you may be confused by some of the jargon surrounding the concepts. You also may be confused by the tools needed. I am going to simplify a few concepts and give you a list of the things that I wish that I understood when I started, and lessons that I’ve learned. Keep in mind that I’m still learning, so this is a message from somebody for whom the concepts have clicked, but expertise has yet to settle in. These are the first steps that you should take.

Steps to Take

  1. It is far easier to learn to program when you can see immediate visual feedback of the code you’ve written. Combine this with:
  2. Programming tools, also known frequently as IDEs, are extremely confusing for beginners. If you do not understand the concepts, then the vast numbers of windows and widgets that help you deconstruct those concepts are only a distraction. Hence:
  3. Start with Processing. You may never have heard of it, but there are several reasons to start here.
    • Per point 1, you will receive immediate visual feedback.
    • Per point 2, the development environment is dead simple and it comes with a lot of working code examples.
    • It is object oriented. You might not know what this means, and you might read a lot of suggestions to start learning with a procedural language (like C), but ignore those suggestions. You can write procedural code in Processing, too. In fact, you definitely will. There’s a brief explanation of this below.
    • It is a superset of Java, a language which many people make a good living coding. Learn Processing and you can hop right into Java without blinking an eye.
    • The best programming book for beginners is Learning Processing, by Daniel Shiffman. If you only ever buy a single programming book, buy this one. It is worth the money.
    • Everything about Processing is free (except the book I recommended).
    • There are thousands of working code examples that run in your browser on Processing.org and OpenProcessing.org.
    • If you do not want Processing to be your primary language, you can migrate from it as soon as you get to the point where things click; a dedicated beginner need not spend more than 2-3 weeks with the language before moving on. I truly believe you can get to the point where things click in that period of time, if you spend time with it each day.
    • Processing is related to Arduino, meaning that you can make small robots and electronic gadgets using the knowledge you learn with processing. Processing and Arduino are a great entry to the “hacking” community.
  4. Pick a very simple project that interests you and start working on it immediately. You may veer away from any book or text that you are following, but your own project will capture your imagination far more than book projects. I have an interest in simulating populations for public health purposes, so I decided to write a small program that would generate populations.
  5. Allow yourself to get frustrated and when you do, step away. Sleep on it. Come back in the morning with a cup of coffee.
  6. Draw flowcharts of what you are trying to achieve and use the flowcharts as a checklist to make certain you are writing what you need in your code.

Ok, here are a few concepts that you will see immediately. Don’t let the language or unfamiliar terms confuse you. Again, these are simplifications. As you learn a language (hopefully Processing), you will understand nuances of these concepts that I am not going to bother to explain here.

A Few Concepts to Consider

  • Method: This is a fancy word for an action. A method is like a verb. Want to make something happen with code? Then you have to write a method or use a method that somebody else wrote to make it happen.
  • Class: Think back to biology and the use of this work in taxonomy. A class is a grouping of properties that describe one or more things. “Mammal” is a class that describes many animals. A class is sort of like a blueprint for a building. Which brings us to:
  • Inheritance: If something is a member of a class, it inherits the properties of that class. The “mammals” class describes animals that have breasts and produce milk. Cows, monkeys, and humans all inherit the property of the mammals class; they are distinct beings, but they all produce milk. When you program, you will write classes. You will write sub-classes. For instance, “cats” is a sub-class of “mammals.”
  • Instance: If a class is a blueprint for a building, and instance is the actual building. You can use the same blueprint to build multiple copies of the building. Such is it in programming: you create ‘instances’ of ‘classes.’ Also known as:
  • Object: You know… this is pretty much what it sounds like. An instance of a class is an object. I have a cat named Robot. He is an instance of the “cat” class. The cat class inherits from the mammals class, etc. If “car” is a class and “mustang” is a sub-class of car, your 1969 red Mustang in the driveway is an object: an instance of the Mustang class.

Now, let’s go to a more specific example:

  • Human: this is a super-class that includes another class:
    • Basketball Player: Any instance of the basketball player automatically inherits the properties of a Human, it’s parent class. This is a class that has some specific actions that it takes. Any instance of the basketball player class should be able to perform actions related to the game of basketball. Those actions are referred to as the class methods. The class methods might include:
      • Pass the ball
      • Catch the ball
      • Shoot the ball
      • Steal the ball
      • Etc…
    • Each individual basketball player that is created is an object. Players know how to interact with each other. In other words, if one player passes the ball, another player catches the ball. This is the fundamental concept behind object-oriented programming. Objects know how to interact with other objects when relevant. Some objects do not know how to interact with each other. If a basketball player through a ball at my cat, Robot, it would bonk him in the head. That’s because Robot does not know how to catch the ball. In other words, the Cat class does not have a “catch the ball” method. However, all mammals know how to eat. So “eat food” is a method of the “mammal” class (in this example). Since the cat class and the basketball player class both are sub-classes of the mammal class, they both inherit the properties and actions of that class, hence, they both know how to eat. The great thing about inheritance is that if you teach a “mammal” how to eat, then all of the sub-classes of “mammal” already know how to eat and you do not have to teach them how to do it again. Cool, huh?

Explanations of Concepts that Confused Me

Now to one of the most confusing things for new programmers: the word void. I cannot tell you how long the word void confused me. This is one of the great barriers to learning how to program and one of the reasons why non-programmers cannot read code. They get caught on the word void. I’ll explain the meaning, but I have to explain a few more things, first.

Back to basketball. For a basketball game you need to track the points scored for each player and for each team. At the end of the game, you choose the winner by comparing team points. A player on the losing team can have the highest individual points scored, though, right? In the case of basketball, “points scored” is what we call a variable. We know at the beginning of the game that we need to track it for each team and for each player, so we have to declare the variable called pointsScored. When you declare a variable, it looks something like this.

int pointsScored;

The int part means that the variable will always store an integer value. The name of the variable is pointsScored. We will used the variable pointsScored to store …. you got it: the number of points that a player or team has scored. Variables can have “scope.” That means that the value associated with the variable falls within a hierarchy so that the variable is only relevant to the object or class that it is associated with. We assign values to variables like this:

pointsScored = 0;

Here is a major difference between normal people and programmers. The equal sign does not mean “equal” in programming. It is called the “assignment operator” because you use it to assign values to variables. The line above means “assign the value of zero to the variable pointsScored.” The “equality operator” is used to check if values are equal to each other. It is represented by two equal signs in a row: ==

The equality operator usually is used in “if” statements. “If myCar == Ferrari then drive fast, otherwise, drive slowly.”

So, back to the assignment operator. The following code would always add 2 points to the value of pointsScored:

pointsScored = pointsScored + 2;

This frequently is shortened to:

pointsScored += 2;

That’s a bit funky and you might have to think about it for a minute. Objects usually have variables associated with them. In some programming languages, you can retrieve or set the value of that variable using a dot operator syntax.

Clay.pointsScored += 2;

Mike.pointsScored += 2;

Since the scope of pointsScored is at the object level, both objects of the same type have a pointsScored variable. Clay and Mike are both instances of the BasketballPlayer object. To calculate the total for the team, you might have:

Team.pointsScored = Clay.pointsScored + Mike.pointsScored;

In other words, set the value of the Team’s pointsScored variable to the sum of Clay’s pointsScored variable and Mike’s pointsScored variable. Now, Team probably is not an instance of the BasketballPlayer class. Since the scope of the pointsScored variable is held at the class level, we can have multiple variables of the same name throughout the application. You probably wouldn’t want to do this, just for clarity’s sake, but it’s one of the possibilities within object oriented programming.

Now, let’s assume that we have another sub-class of “mammal” called mathematician. Create an instance of the mathematician class: let’s call him Newton. His sole purpose in life is to do what you tell him to do. These actions, methods that he can perform, either require him to return results back to you or they don’t. If you tell Newton to go eat dinner, he does not return anything back to you: he simply goes to dinner. However, when you need Newton to add two numbers together, you expect a result back.

To make him return the result, you have to tell him the two numbers that you want him to add together and then you have to tell him the format of the number that you want him to return to you. Let’s say that you want him to add two integers together and return a number to you that is the sum of those integers. You would write a method for Newton called addTwoNumbers(). When you see parenthesis following a word, it’s probably a method.

You have to do a few things here: tell Newton that you want him to addTwoNumbers, tell him what the numbers are that you want him to add, and tell him that you want an integer in return. When you describe the addTwoNumbers method in the mathematician class, that is where you specify how you want the action to happen and what type of number you want in return. The code in the mathematician class would look something like this:

int addTwoNumbers(int firstNumber, int secondNumber)
{
return firstNumber + secondNumber;
}

Whoa! What’s going on? First of all, “int” means “integer.” The red int specifies the type of number that you want your mathematician to return to you when you ask him to addTwoNumbers(). You are saying that you want an integer back in return. The blue parts are the parameters that you are giving to the mathematician — the numbers that you want added. You have to tell the mathematician that you are handing him two integers, called firstNumber and secondNumber. The blue part in addTwoNumbers(int firstNumber, int secondNumber) describes the types of parameters that you are giving to the mathematician. So the first line effectively says, “Hey mathematician, I want you to addTwoNumbers, an integer firstNumber and an integer secondNumber, and tell me the result as an integer.”

Now, when you write the code for this method, you have to realize that the variables within the parenthesis are local to the method, with regards to scope. That means that you can refer to firstNumber and secondNumber anywhere within the curly braces { }, but you cannot refer to it anywhere else because the computer will not know what you are talking about. In fact, when you wrote the method, you declared the variables, for the very first time, within the addTwoNumbers() parenthesis. More on scope in a minute.

Computers are stupid, but they are VERY obedient. They do EXACTLY what you tell them to do. If you make a mistake, they make a mistake. The computer does not understand what addTwoNumbers() means. Luckily, it understands the + sign and how to do addition. Hence, you have to tell it what to do when you ask it to addTwoNumbers(). The code inside of the { } brackets tells it what to do in that instance. { return firstNumber + secondNumber; } means that this method should add the integer firstNumberto the integer secondNumber and then it is done. Since you told it that you wanted an integer back, it sends you the value of firstNumber + secondNumber as an integer.

One more thing: the computer is so stupid that it doesn’t know when to stop, so you have to put a semicolon at the end of each statement to let it know that it’s done with that statement. Some languages do not require this! You’ll discover which do and which don’t as you learn to program.

Ok, so we taught the mathematician class how to addTwoNumbers(). If you remember, we created a mathematician instance called Newton. How do you tell Newton that you want him to addTwoNumbers and how to you tell him which numbers? Like everything else, this will vary from language to language. It is, however, common to see code that looks like this:

x = Newton.addTwoNumbers(10, 5);

Here you asked Newton to tell you what 10 + 5 equals and to store that value in the variable x. A variable is basically a container. Think of x as a post-it note: the above code causes Newton to write the number 15 on a post-it note. The cool thing is that you can send the post-it note into the same method again, even multiple times! So, you could do either of these:

y = Newton.addTwoNumbers(x5);

or

z = Newton.addTwoNumbers(xx);

The first would cause Newton to write the number 20 on a different post-it note (y) and the second would cause him to write 30 on yet another post-it (z).

A word of caution here: the parameters can only be integers because that is how you defined the method. This would cause an error:

x = Newton.addTwoNumbers(3.145);

3.14 is NOT an integer. It is referred to as a floating point number. Computers are stupid, remember… None of your mathematicians will know what to do with the above statement. They will just tell you “Error! Error!” And here you thought Newton was smarter than that…

Programming languages that are very strict about the differences between integers and floating point numbers (among other things) are considered to be “strongly typed.” Some languages are better at figuring out what’s going on: Ruby is one of those languages. It makes a good second language after Processing, though you will not receive visual feedback from your code – mainly feedback in a command window or in Terminal.app.

Void

Hey! I didn’t forget. Remember that we want Newton to eat dinner, too. When we tell him to eat dinner, we don’t need him to return a result to us — you don’t want the dirty dishes, do you? I didn’t think so. In the mathematician class, we might have another method called eatDinner(). Computers being stupid, we have to explicitly state that we do not want the dirty dishes brought to us — or that we do not want a value returned from the method, and that’s what the word void means when you see it in programming. The method would look something like this:

void eatDinner()
{
// Some code that explains how to eat dinner would be here
}

Pretty simple, eh? The eatDinner() method does not have any parameters. If we wanted to be able to tell our mathematicians to eat something specific for dinner, we might have another method that looked like this:

void eatThisForDinner(a food item that you specify)
{
// Some code that explains how to eat a specific food item
}

You know what is cool here? You could have another class called “food items” and then you could create specific instances of the food item class, maybe one called tunafish. If you told Newton.eatThisForDinner(tunafish); it would send instructions to Newton to absorb the nutritional properties that the tunafish has and then you could make the specific instance of tunafish disappear. Cool!

Public and Private

These are two other terms that you will see when you first start programming. “Public” basically means “anybody can perform this method” and “private” means “this is a secret method that only people of my class can perform.” Let’s assume for a second that we have a method called performCalculus(). I don’t know about you, but I think that Calculus is difficult. It’s pretty much a secret to most people — if they want to performCalculus(), they have to be a member of the mathematician class. That being the case, when you define the method in the mathematician class, you would make it private. The method code might look like this:

private float performCalculus(one number, another number)
{
// Secret calculus code would be here
}

In this case, I could write Newton.performCalculus(xy); or Leibniz.performCalculus(x, y); but I would not be able to write Clay.performCalculus(x, y); because I am not of the mathematician class. Newton or Leibniz would return a floating point number to you in this case.

Now, if you want anybody to be able to tell Newton or Leibniz to eat dinner, you would make it a public method so that people in other classes could call it. I’m not a mathematician, so I would not be able to tell Newton to eatDinner() unless it was a public method. This is  a great simplification of a concept called encapsulation. You also will hear the term scope used in these discussions. For example, “What is the scope of that variable or method?” The method might appear something as follows:

public void eatDinner()
{
// Code that  explains how to eat dinner
}

Finally, you can set the scope of variables in a similar manner. Sometimes you will have “global” variables that every object in your application needs to reference. Back to basketball… everybody from the ref to the players to the coach need to know the time remaining in the game. They may call plays differently, change strategy, decide whether to foul, etc… differently depending on how much time remains. In this instance, you would make a global variable for timeRemaining.

That’s about it!

Go download Processing, buy Shiffman’s book if you can, and get started! It’s easier than it seems, especially if you understand what some of these words mean as you get into it! Good luck and let me know if this was helpful. If you upload anything to openprocessing.org, let me know – I’d love to take a look. :) If there’s anything else (simple) that you don’t understand, let me know and I will take a stab at explaining it.

Written by Clay

January 22, 2010 at 15:32