Fibonacci stream

February 4th, 2008

The Fibonacci sequence: teacher of recursion for so many Computer Science students. But can it also teach us about streams? Yes! The function to build a stream (in Javascript):

var fib_stream_maker = function() {
  return (function() {
    var a = 0;
    var b = 0;
    var c = 1;
 
    return function() {
      a = b;
      b = c;
      c = a + b;
      return c;
    }
  })();
}

Let’s break this down so Ben can follow along. First, the inner most function:

return function() {
  a = b;
  b = c;
  c = a + b;
  return c;
}

This anonymous function returns the next number in the sequence. Looking one level of scope higher, we see the variables a, b, and c declared:

function() {
  var a = 0;
  var b = 0;
  var c = 1;
 
  return function() {
    a = b;
    b = c;
    c = a + b;
    return c;
  }
}

So we initialize the variables and then return a function that increments those variables, local to the inner function’s scope, so we can have multiple instances of the function running without collision of variables. To build the stream factory, we wrap the initialization function in parentheses, creating a continuation, and then execute the wrapped function, creating an initialized fib stream function. This is then set to return when the fib_stream_maker is called as a function.

var fib_stream = fib_stream_maker();
 
fib_stream(); // returns 1
fib_stream(); // returns 2
fib_stream(); // returns 3
fib_stream(); // returns 5
fib_stream(); // returns 8, etc...

This is only touching the surface of streams but I thought it was pretty cool that the Fibonacci sequence can be utilized to teach such important concepts as continuations and streams. Code on!

*Update*

While explaining the inner workings of the above code to CD, she asked a very astute question, one that Ben probably would not have, “What about going backwards in the stream?” A just question. Let’s look at a table of how the values of a, b, and c act as the stream goes forward first (this will help us design our algorithm later).

  a b c Returns
Creating fib_stream 0 0 1  
fib_stream(); 0 1 1 1
fib_stream(); 1 1 2 2
fib_stream(); 1 2 3 3
fib_stream(); 2 3 5 5

So to go backwards, what do we need to do to values of a, b, and c? We need to assign b’s value to c, a’s value to b, and the difference of c and b to a, and still return c. In code, this would look like:

c = b;
b = a;
a = c - b;
return c;

To integrate this into the above example, we need to pass a boolean parameter to the inner-most lamda function and test to see whether to forward or reverse the stream. Let’s see the inner-lamda now:

return function(go_forward) {
  if ( go_forward ) {
    a = b;
    b = c;
    c = a + b;
  } else {
    c = b;
    b = a;
    a = c - b;
  }
 
  return c;
}

We may want to put an additional test to see if we are at the beginning of the stream again:

return function(go_forward) {
  if ( go_forward ) {
    a = b;
    b = c;
    c = a + b;
  } else if ( a == 0 && b == 0 ) {
    ; // do nothing
  } else {
    c = b;
    b = a;
    a = c - b;
  }
 
  return c;
}

Let’s see it all as one big fun function:

var fib_stream_maker = function() {
  return (function() {
    var a = 0;
    var b = 0;
    var c = 1;
 
    return function(go_forward) {
      if ( go_forward ) {
        a = b;
        b = c;
        c = a + b;
      } else if ( a == 0 && b == 0 ) {
        ; // do nothing
      } else {
        c = b;
        b = a;
        a = c - b;
      }
      return c;
    }
  })();
}

And there you have it. Thanks CD for bringing up this interesting idea! What a nerd!

Save the Tongass

February 1st, 2008

Add your name to the list of those that want to save the Tongass (read more here).

Call (202-205-1661), write, or email Abigail Kimbell of the US Forest Service and let her know your disapproval. The form email sent from the NRDC site is:

Chief Abigail Kimbell, U.S. Forest Service
1400 Independence Avenue, SW
Washington, DC 20250-0003

Dear Forest Service Chief Kimbell ,

I strongly urge you to protect all remaining roadless areas in
the Tongass National Forest and to direct Forest Service
officials not to increase costly road-building or logging in
this precious national treasure. Roadless areas comprise our
last wild places and they should not be made vulnerable to
logging, drilling or other development. As a nation, we must
continue to safeguard the heart of our national forest legacy by
protecting the ecological health, wildlife habitat, drinking
water and recreational value of those few American forests still
unspoiled by roads.

It makes no sense to use taxpayer subsidies to destroy the
Tongass, America’s great rainforest and one of the crown jewels
of the national forest system, and jeopardize all that it offers
for local hunting, fishing, recreation, tourism and subsistence
use.

Time and again, citizens like me from around the country have
called upon you and the administration to protect the Tongass.
It’s time to heed this overwhelming public sentiment by
preserving, not destroying, the remaining wild stretches of this
truly unique part of our natural heritage.

Sincerely,

YOU!!!

Save $150 Billion Much?

February 1st, 2008

It’s a sad state of affairs that we as voters must wade through so much posturing and pandering by the presidential candidates. Particularly hard is when we find out after they are elected that their words were vaporous and meaningless. What’s a voter to do?

A study released January 29th of this year by the National Taxpayers Union Foundation helps tax payers cut through the facade and see the real truth, expressed in hard numbers. Keep in mind that the United States has trillions of dollars ($9,200,874,834,693.13) in debt, is spending close to $1 trillion a year on Iraq and Afghanistan, and is facing the housing market implosion. Now, with all this economic unrest, which candidates actually want to do something about it and save some dough?

The four respective frontrunners in the two parties (John McCain, Mitt Romney, Hillary Clinton, and Barack Obama), proposed overall fiscal policy agendas whose net effect would raise annual federal outlays between $6.9 billion and $287.0 billion.

The top-tier GOP candidates often portrayed as “conservative” (Mitt Romney and Mike Huckabee) actually called for significantly larger spending hikes ($19.5 billion and $54.2 billion, respectively), than the so-called “moderate conservative” (John McCain, $6.9 billion).

Among Democrats, Barack Obama, often described as ideologically more “moderate” than Hillary Clinton, actually has the larger agenda of the two ($287.0 billion vs. $218.2 billion).

Defense-related spending items received the highest proposed spending increases among Republican candidates. Huckabee and Romney, for example, offered $67.2 billion and $40.6 billion, respectively. Among Democrats, Clinton’s biggest boost goes toward health care ($113.6 billion) and Obama’s for economy, transportation, and infrastructure ($105.0 billion).

Two of the eight candidates proposed sufficient spending cuts that more than offset their new spending plans: Rudy Giuliani (-$1.4 billion) and Ron Paul (-$150.1 billion).

Taking into account that Rudy Giuliani has dropped out, this makes Ron Paul the only candidate that actually wants to save the country some money, and he wants to do it on a large scale. Why are we pouring in so much money in taxes, to support a government that doesn’t represent us? Why would you support a candidate that wants that trend to continue? Where is this money going to come from?

Would you rather not pay income taxes? I know I would. What if you got to keep an extra third of your income? Don’t you think that’s a bigger chunk than a proposed $300 tax rebate Congress is now considering to “stimulate” the economy? I know it is significantly more for me. I would rather spend the money that I earned than some small rebate the government gives me. We don’t know the source of that rebate either. The administration is currently engaged in deficit spending, racking up more debt to pass on to future generations. How long until China calls in those debts?

It’s time to make the government stop spending, and the only way to do that is by electing Ron Paul, the only candidate left that is 100% for real about cutting spending and saving US citizens their hard-earned income. Read his views, compare them with an open mind to the other candidates, and you’ll see Dr. Paul is truly about getting our country back on track.

Join the REVOLUTION

MySQL -> CSV

January 30th, 2008

Always on the lookout for increases in efficiency, I love when I find a slick snippet of command line goodness that makes a hard sounding task simple and quick. I was tasked with creating an email list from a database and putting it into a csv format, and had only the command line to interface with the DB. My first attempt revolved around using the SELECT … INTO OUTFILE syntax. Unfortunately, I was unable to write out to a file with the DB user I had access to. What’s a fella to do?

Unix pipes to the rescue.

First, the whole command:

echo “select * from example;” | mysql -u user -p dbname | tr ‘^V^I’ ‘,’ > filename.csv

Let’s break this down, in case Ben is reading and can’t follow along. The echo statement contains your query. It is sent to the mysql command, which connects you to the database and executes the query, returning the data in tab-delimited format to the console. The tr command reads from STDIN, and replaces tabs (Ctrl-V Ctrl-I) with whatever delimiter you want (in this case the comma). The final touch is sending it to a file of your choosing.

*Note* - You actually have to type the Ctrl-V Ctrl-I when entering this command. Copy/paste won’t cut it in the example above.

*Note* - You typically do not want to actually enter your mysql password on the command line, as commands run are typically logged. Omit the password to force mysql to ask for it (it won’t interfere with the query). And if you don’t have your mysql access password protected, WTF? You’re asking for trouble.

So there you have it. Simple, easy to follow, effective. As always, this example can be extended into a variety of different ways. It’s up to you to figure it out (you can, of course, pay me to figure it out).

Happy MLK Day

January 21st, 2008

As we celebrate the life and message of Dr. Martin Luther King, we need to consider his work unfinished. With the presidential campaigns in full force, spreading their vision for the future, it has become clear that one candidate, for me, is truly offering a world view that makes sense.

Dr. Ron Paul is bringing a vision that actually differs from the other candidates. He is challenging the status quo and it is working because there are constant attempts to exclude him from the debates, from political coverage, to label him “un-electable” (thanks Faux…I mean Fox News). Despite this, Dr. Paul’s message is building enthusiasm and excitement across the country.

There are many issues important to me that the candidate must offer solutions to for me to be interested in them (a note: we are interviewing these candidates to be our president, so we need to be as demanding as possible so we get the best. Don’t settle for one based on party lines; consider each viewpoint, which means actually reading about candidates you don’t agree with). First, and probably most important, is Iraq and our withdrawal from Iraq. Goodbye most of the Republicans. Dr. Paul wants us out and for so many good reasons. I believe Dr. Paul is 100% correct in his assessment of why 9/11 happened (speaking of, does Giuliani appear if you say 9/11 three times, like Beetlejuice?). Our foreign policies, our military presence in so many foreign countries, our lust for oil all contribute to us treating other countries, particularly in the Middle East, as second- or third-class world citizens. Sound familiar? Think back to this country’s struggles with civil rights and all the emotions and violence it created (Civil War anyone? KKK anyone). Why do we find it so shocking that we treat foreign governments in much the same way blacks were treated, and the people of those governments lash out at us much the same way the African-Americans lashed out at the establishment for the last 150 years? Fortunately there were voices like MLK to calm the violence and provide a peaceful plan to uplift society. Ron Paul speaks of this peace, on the global scale, and we need to heed that voice!

A second issue, which, while just barely lower on my list than the war, probably is the most important issue our country is facing, and that issue is the economy. For too long the Federal Reserve (a private institution) has held our money supply in its clutches. The FR has gotten us so far away from the Gold Standard that our money is severely devalued. Talking about Nevada and its recent caucus, Dr. Paul wrote in his newsletter:

Nevada, by the way, is known as the Silver State for a reason-its great mining industry produced the precious metal for the beautiful silver dollars minted at the fabled Carson City mint. These constitutional coins, include .775 ounces of silver, in accord with the Coinage Act of 1792. Today these coins, worth $1 in my father’s day, have about $14 in silver. That is, the dollar is worth 1/14th of what it was, thanks to the counterfeiting Federal Reserve.

1/14th of what they were! Economic theory is hard to swallow for most, I know, but this is a pretty clear example of the dire position our economy is in. To make matters worse, this was the situation before the housing bubble burst, and before the Iraq War. You toss those two economic clusterf@cks into the mix and its no wonder the word “recession” is tossed about so freely. From an economic standpoint, we’re sending billions of dollars each year to Iraq, in the form of troops, aid, weapons, etc, and yet we are in the midst of a huge housing crisis, our dollar is severely devalued, and we are being loaned money at an alarming rate by China to finance the war. Do we really think China will not use our debt to them as leverage to get what they want? Since when did the United States put themselves in the pocket of a communist country? And from all the discussion, not a single candidate, aside from Dr. Paul, is seeing the connections and planning accordingly. They want to fix the effects, rather than address the causes, and it seems most want to print more money to assuage the economic crisis.

It is clear to me that Dr. Paul is the guiding light that truly offers the right kind of change, a principled change, based on sound reasoning and policy, and brought to us by a principled man. No candidate can be one-size-fits-all to the American people; we are too diverse for that to ever be the case. However, I believe Dr. Paul’s message to benefit most the common man, middle- and lower-income families, and the American image abroad. Isn’t it time we had a president who actually had policies intended to let Americans live as they see fit and not as some bureaucrat in Washington sees fit?

If so, read his thoughts on the issues and donate to Dr. Paul’s campaign today! Join the REVOLUTION!

Portland is fun

December 8th, 2007

While the weather has not cooperated and given me many sunny days yet, I have been enjoying exploring the cyber-presence Portland has, in particular the Craigslist offerings. Today, however, brings a new entry in the NW Nerdery: a movement to rename 42nd Ave to Douglas Adams Blvd. The site, rename42nd.org, is making a serious effort to have the 42nd Ave renamed in honor of Douglas Adams, most notable for authoring the Hitchhiker’s Guide to the Galaxy series. My inner geek smiles wide for this effort and hope they succeed. If you are a Portlander, support the movement. I know I am…

7 Days, 7 Nights, 7 Minutes

October 19th, 2007

One of the projects I’ve been helping get off the ground is I Live Inspired, an inspirational text-messaging service. The site is good, and the concept is great. One can never have too much inspiration.

The founders, Rob and Chris, are on a mission. They are seeking an audience with the Dalai Lama in Indiana and are walking 7 days in hopes of getting a 7 minute audience. They are also keeping a blog of their adventures. These guys are not much older than me and are trying to get a positive service off the ground. Whether they have audience with the Dalai Lama or not, the experience of the walk, the people they’ve met thus far, and the people they’ve yet to meet, will change their lives. And we get to share in that through their writing.

So take a minute, read up on what the future of America is up to, and if you want some extra inspiration delivered to your phone daily, consider signing up for one of the many great communities at I Live Inspired.

* Disclaimer: While I have helped create the site, I do not receive any compensation for spreading the word. I think its a great service and deserves notice.

Pambiche

October 5th, 2007

While highlights abound on the Portland tour, one in particular deserves mention. I’ve dined at some pretty sweet places and eaten some fairly exotic foods. While they’ve all been good and memorable, I found that a little Cuban place in Portland has taken the top spot in my dining history. What’s amazing about Pambiche is the unassuming atmosphere surrounding the restaurant. Walking up to, I had no idea what I was about to experience.

Sadly, I was only able to eat there once while in the city, so I can only speak to one dish, Ajiaco. Described as a “one pot meal that comes brimming with a variety of tropical roots and vegetables, corn dumplings, creole seasoned pork and beef”, this tasty meal was unlike any other food I’d tasted. Very subtle flavors and aromas with each spoonful pleased my tastebuds and tummy. And while Cuban food is not traditionally spicy, Pambiche had a homemade spicy sauce which complimented the dish wonderfully.

I am not a food critic so it’s hard to do the experience justice. Next time Portland dining is available, head over to 2811 NE Glisan and taste it firsthand. I plan on doing just that!

Don’t call this number

September 9th, 2007

Telemarketers suck. Soon they will be getting your mobile number. To prevent unsolicited phone calls, give a ringy dingy to 888-382-1222 and take a minute of your time to get on the national Do Not Call list. Make sure you are calling from the phone with the number you are registering.

This public service announcement brought to you by the number 15, the number 17, and the letters C and D.

August 27th Emails

August 14th, 2007

I just received an email about August 27th and the proximity of Mars to the Earth. The email claims that Mars will be close to 34 million miles from Earth, the closest it will get for another 2000 years, a distance which will cause it to appear as bright as the moon in the night sky. While the claim is valid, it is what the email leaves out that makes it annoying: the year. This event occurred in 2003, and while Mars was the 4th brightest object in the sky (behind the sun, moon, and Venus), it was still just a small point of light.

You can read more at NASA’s page concerning the hoax. It is dated from 2005, but explains the email hoax (which has been circulating since 2004) and what is true and misleading about it. So if you get the email, please don’t forward it on. It’s so 2003…