Life as Clay

Archive for the ‘Technology’ Category

New Population Pyramid Generator

leave a comment »

I created a new OS X population pyramid generator application, called Pyramids. Click here to see it in the Mac App Store. It’s $0.99. If you have a Mac and need to make population pyramids with any regularity, or even just a single one, then give it a shot!



Using Nokogiri and Ruby on Rails to grab citations from PubMed

with 12 comments

Update: I put a working example up on github (Rails 3.0.4 and Nokogiri 1.4.4):


Following on the last post… I needed to provide to a client a custom database of PubMed citations, links, datasets, and other information related to a product area I was researching. The hardest part about this was understanding PubMed’s eutils and their .xml formats.

I did not want to manually enter the citation information. I wanted to avoid Zotero and other similar services because I wanted to integrate the data across domains and use the database that I was developing for them as the basis for a paper I wrote. For the PubMed citations, what I wanted to be able to do was to go to PubMed, perform a search, find an interesting citation, copy the PubMed URL, paste it into my Rails application, which would use the URL to query PubMed in XML format and populate my app’s database with that entry.

I have two models that play into this interaction: Article and Journal. I should note that I’m using Nokogiri to parse the XML and thoughtbot’s Paperclip gem to attach articles when they are available freely. This was done using Rails 2.3.5 and Ruby 1.8.7.

Here’s how the model files look:


class Journal < ActiveRecord::Base   attr_accessible :name, :description, :url, :short_name      has_many :articles      validates_uniqueness_of :name   validates_presence_of :short_name   validates_presence_of :name      before_save :make_short_name      def best_name     if !self.short_name.nil? && self.short_name.length > 0
      return self.short_name


  # Makes sure that a new journal has a short name in case one isn't entered.
  def make_short_name
    if self.short_name.nil? || self.short_name.length == 0
      self.short_name =

The Article model is a little more complicated. The logic that I’m using the parse the XML isn’t great, but I’ve found that the structure changes from article to article. I’m still refining it and will update it when I’m finished, after I’ve found the 90% of article that auto-import.


class Article < ActiveRecord::Base   require 'open-uri'   attr_accessible :pubmedlink,                    :article_title,                    :abstract,                    :authors,                    :affiliations,                    :pubdate,                    :pubmedid,                    :journal_id,                    :journal_volume,                    :journal_issue,                    :journal_pages,                   :fetched,                   :thearticle_file_name,                   :thearticle_content_type,                   :thearticle_file_size,                   :thearticle_updated_at,                   :thearticle                      has_attached_file :thearticle,                     :path => ":rails_root/public/system/uploads/:class/:id/:basename.:extension",
                    :url => "/system/uploads/:class/:id/:basename.:extension"
  belongs_to :journal
  before_save :make_pubmedid
  validates_uniqueness_of :article_title

  def citation
    cit = ""
    if self.journal_id != nil && self.journal_id > 0
      cit += self.journal.best_name + ". " + self.pubdate.year.to_s + " " + self.pubdate.strftime("%b")
    if self.journal_volume != nil && self.journal_volume.length > 0
      cit += "; " + self.journal_volume
    if self.journal_issue != nil && self.journal_issue.length > 0
      cit += "(" + self.journal_issue + ")"
    if self.journal_pages != nil && self.journal_pages.length > 0
      cit += ": " + self.journal_pages
      return cit


  def make_pubmedid
    if self.pubmedlink != nil && self.pubmedlink.length > 0 && self.fetched == false
      regex =[0-9]{4,10}/)
      matchdata = regex.match(self.pubmedlink)
      self.pubmedid = matchdata[0]
      self.fetched = true

  def pull_pubmed_data(theID)
    @doc = Nokogiri::XML(open("" + theID.to_s + "&retmode=xml").read)

    # The title and abstract
    self.article_title = @doc.xpath("//ArticleTitle").collect(&:text).to_s
    self.abstract = @doc.xpath("//AbstractText").collect(&:text).to_s

    # Setting up the authors
    first_names = @doc.xpath("//ForeName").collect(&:text)
    last_names = @doc.xpath("//LastName").collect(&:text)
    full_names = []

    i = 0
    last_names.length.times do
      the_name = first_names[i].to_s + " " + last_names[i].to_s
      full_names.push the_name
      i += 1
    self.authors = full_names.join(", ")

    # Affiliations
    self.affiliations = @doc.xpath("//Affiliation").collect(&:text).to_s

    # Publication Date - Check if the complete date is at the top. If not use the pub med date.
    theyear = @doc.xpath("//PubDate/Year").collect(&:text)
    theyear = theyear[0]
    themonth = @doc.xpath("//PubDate/Month").collect(&:text)
    themonth = themonth[0]
    theday = @doc.xpath("//PubDate/Day").collect(&:text)

    if theyear.nil? || themonth.nil? || theday.nil? || theyear.length == 0 || themonth.length == 0 || theday.length == 0

      theyear = @doc.xpath("//PubMedPubDate[@PubStatus='pubmed']/Year").collect(&:text)
      theyear = theyear[0]

      themonth = @doc.xpath("//PubMedPubDate[@PubStatus='pubmed']/Month").collect(&:text)
      themonth = themonth[0].to_i
        month_done = 1
      if themonth < 10
        themonth = "0" + themonth.to_s
        month_done = 1

      theday = @doc.xpath("//PubMedPubDate[@PubStatus='pubmed']/Day").collect(&:text)

    if month_done != 1

      themonth = case themonth || "01"
        when "Jan"  then "01"
        when "Feb"  then "02"
        when "Mar"  then "03"
        when "Apr"  then "04"
        when "May"  then "05"
        when "Jun"  then "06"
        when "Jul"  then "07"
        when "Aug"  then "08"
        when "Sep"  then "09"
        when "Oct"  then "10"
        when "Nov"  then "11"
        when "Dec"  then "12"


    if theday.length == 0
      theday = "01"
    elsif theday[0].to_i < 10       theday = "0" + theday[0].to_s     else       theday = theday[0].to_s     end          thedate = theyear.to_s + "-" + themonth.to_s + "-" + theday.to_s     puts "thedate: " + thedate.to_s     self.pubdate =, themonth.to_i, theday.to_i)          # Either referencing the proper journal or creating a new one     thejournal = @doc.xpath("//Journal/Title").collect(&:text)     thejournal = thejournal[0]          theshortname = @doc.xpath("//MedlineTA").collect(&:text)     if theshortname.length == 0       theshortname = ""     else       theshortname = theshortname[0]     end          thejournalid = Journal.find(:first, :conditions => ['lower(name) = ?', thejournal.downcase])

    if !thejournalid.nil?
      self.journal_id =
      @journal = => thejournal.to_s, :short_name => theshortname.to_s)
      thenewjournal = Journal.find(:first, :order => 'created_at DESC')
      self.journal_id =

    # Save the volume, issue, and pages
    thevolume = @doc.xpath("//JournalIssue/Volume").collect(&:text)
    thevolume = thevolume[0].to_s if thevolume.length > 0
    self.journal_volume = thevolume if thevolume.length > 0

    theissue = @doc.xpath("//JournalIssue/Issue").collect(&:text)
    theissue = theissue[0].to_s if theissue.length > 0
    self.journal_issue = theissue if theissue.length > 0

    thepag = @doc.xpath("//Pagination/MedlinePgn").collect(&:text)
    thepag = thepag[0].to_s if thepag.length > 0
    self.journal_pages = thepag if thepag.length > 0



The journals_controller.rb file is pretty standard. So is the articles_controller.rb file. Here it is as an example:


class ArticlesController < ApplicationController   def index     @articles = Article.all(:order => "pubdate DESC")

  def show
    @article = Article.find(params[:id])

  def new
    @article =
    @journals = Journal.all(:order => :name)

  def create
    @article =[:article])
      flash[:notice] = "Successfully created article."
      redirect_to @article
      render :action => 'new'

  def edit
    @article = Article.find(params[:id])
    @journals = Journal.all(:order => :name)

  def update
    @article = Article.find(params[:id])
    if @article.update_attributes(params[:article])
      flash[:notice] = "Successfully updated article."
      redirect_to @article
      render :action => 'edit'

  def destroy
    @article = Article.find(params[:id])
    flash[:notice] = "Successfully destroyed article."
    redirect_to articles_url

Here are the view files for articles:


<div class="toolbar">
<th>Article Title</th>
<tr class="<%= cycle('rowA', 'rowB') %>">
<td><strong> </strong>

		  <em> </em></td>
<td class="deletelink"></td>


<div class="toolbar">
	  <strong>PubMed Link:</strong>

	  <strong>View the Article:</strong>

  <strong>Article Title:</strong>







  <strong>Journal Volume:</strong>

  <strong>Journal Issue:</strong>

  <strong>Journal Pages:</strong>


<h3>Enter a link to an abstract on PubMed and click Submit or fill out the information below</h3>

		There currently is no file attached.

<hr />

The Paperclip gem requires :html => { :multipart => true } at the top of the _form file. It’s a very simple gem to use and very powerful. There are Google Groups for both Paperclip and Nokogiri, should you need additional assistance setting them up.

Leave me a comment if this helps you with either Nokogiri or with extracting data from PubMed!

Written by Clay

July 9, 2010 at 18:18

Posted in Code, Ruby, Technology

Tagged with , , , ,

How to query PubMed and retrieve XML results

This seems like it should be a simple thing to figure out how to do on the PubMed website — return a single result as XML. If you visit PubMed, there is a “Display” link at the top left that allow you to view an entry in XML format, but when you select that option, the URL changes to the vanilla PubMed URL. Anyhow, let’s say you go to PubMed and look at a particular article:

You can retrieve the same result in XML by simply going to this URL:

Other formats are available and outlined on the PubMed help site. The help files on the site are not particularly easy to search, so it took me forever to find this info.

When you use the URL above, the page is designed to create XML that displays properly in the browser — not XML parsing by Ruby or another language. For that, you have to use the eutils. The proper link for returning XML that you can parse with nokogiri or another gem is:

Written by Clay

July 6, 2010 at 13:07

Posted in Public Health, Technology

Tagged with ,

Closing a Haitian field hospital

leave a comment »

Part of life is realizing when to throw caution aside and step forward to partake in something interesting. I did that and traveled to a field hospital in Fond Parisien, Haiti back in the middle of February. I found there a fantastic center for patient care, along with dozens of hard-working and committed local staff and volunteers. They had a data management problem — too many spreadsheets, too many lists, not enough organization. It was a burden even to produce a simple census of the tent camp patient population.

I quickly whipped together a simple Ruby on Rails EMR system based on the structure of a blog. Each patient had a medical record that was a blog entry and with each subsequent medical evaluation or event, a “comment” was added to their medical record. This improved continuity of care, helped staff remember when to give important medications, and generally improved the medical stance of the facility. (Note: the “comments” were structured medical notes, not just free text…)

There is a huge number of factors that play into the care of patients in a field hospital. Sometimes those factors do not all work well together. The hospital is closing this week, due to a lack of funding and a deteriorating security situation. Now, I get to return to the field to help disassemble the systems that I helped put together only a few months ago.

Data systems must be flexible during humanitarian response, I learned. In spite of a strong internal voice telling me to make certain that all of the data is normalized and collected in a proper format, the truth is that patient care comes first and the needs of staff change over time. When you have 300 patients and 30 doctors for a sustained period of time, you develop an understanding of what they can enter into a simple patient charting system. When you then find yourself with 300 patients and 7 staff members, you no longer can rely on the earlier learnings. The people are busy and they will not change, but we can change our data systems to accommodate their overload.

That is exactly how the Fond Parisien EMR system changed over the past few months. It left me with many questions about how to create the proper types of “data integrity tiers” that support different stages of a humanitarian response effort. GIS is vital in the beginning — proper patient discharge sheets are vital in the end, when GIS no longer is in use. How do you reconcile those changing needs into a unified system?

I look forward to helping close the hospital and to the lessons that we learn from this deployment. The staff who poured their lives into the effort surely will continue to come up with new insights based on this experience for years to come. I look forward to tagging along to capture those insights, in hopes of developing the skills and knowledge necessary to develop better data systems for humanitarian response in the future.

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 and
    • 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);


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


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, 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

Public Health & Technology: Confronting the Realities of Disaster

leave a comment »

My true interest, the one that drives my pursuit of programming, is the use of technology to improve response during public health emergencies. I do not write a lot about it on this blog because I currently am not directly involved in emergency response or recovery work. Previous experience, both post-tsunami and post-Katrina, taught me that technology, when deployed properly, can save time, ease minds, and help keep disaster survivors safe. Technology becomes a sharp double-edged sword during times of crisis, though, because if it does not work as expected when needed, it can confuse response efforts and effectively harm the people it is meant to help.

The devastation in Haiti from yesterday’s earthquake is severe and people there are suffering. Families search desperately for missing members who may be buried under the rubble of a collapsed building. People probably cannot get the fresh water they need or visit the markets that usually supply their food. I once saw a family of three, several days after Katrina hit New Orleans, dehydrated, tired, ragged, dirty, and exhausted, walking towards the Red Cross headquarters building in search of diapers for their baby. In contrast to conditions in Haiti, that now seems like a problem of the privileged.

How does technology shoehorn itself into these situations of human suffering? How do we use it to save lives? Find missing children? Prevent disease? Provide water? Understand that people need diapers for their children? The answers are not obvious and they may differ with each unfortunate disaster.

I believe in the power of technology to transform disaster response. So today, as I sit at my desk and build a database, surrounded by more than I need and the luxuries of a modern life of gadgets, my head will be elsewhere, wondering how I could leverage those devices in Haiti, to help improve the lives of the people suffering.

Written by Clay

January 13, 2010 at 12:39