16 December 2009

PHP array_insert

I had the need the other day to create an ordered collection object. I wanted to be able to add elements to the end of the collection as well as at any point in the middle of the collection. Since I was using PHP as the language to create this object, an array was the obvious construct to use as the internal implementation for this collection. Adding elements to the end of an array is trivial, but inserting elements into the middle of the array turned out to be a bit more difficult.

My first thought was that PHP has all kinds of array functions so there must be an array_insert function. This assumption turned out to be wrong. My second thought is that I would have to cut the array into two pieces, insert the new element to the end of the first piece and then glue to two arrays back together. In fact, I coded this before reading the documentation for the array_splice function more closely.

The array_splice function has two optional parameters which are very helpful in creating an array_insert function. The first optional parameter is the length option. This option specifies how many elements to remove from the original array starting at the specified offset. The second optional parameter is the replacement option. This parameter specified what to replace the removed elements with. So, in other words, you can tell array_splice to remove 6 elements from an array starting at offset 2 and to replace the 6 elements with what ever is in the replacement array.

This is perfect for mimicking an array_insert function. If you specify to remove 0 elements and pass in the new element as an array of 1 item, it gets inserted at the specified index. Now for the example:
function array_insert($array, $index, $new_element)
{
    return array_splice($array, $index, 0, array($new_element));
}
There you have it, array_insert nice and clean and optimized in c.

13 September 2009

Foundation Series


Right before Candace went to the hospital to deliver Genevieve she was trying to find a good book to read. A good friend suggested to Candace that she read the Foundation Series by Isaac Asimov. A few day later I picked it up, as it was sitting near by, and started reading it. Each Chapter was only a few pages long. This is a very positive quality in a book for me. I usually only have 5-10 minutes at a time to read, so a short chapter lends itself to my reading habits. As the series went on the chapters became longer and longer which meant that as I moved through the series it started to take longer and longer to finish each book. I read only the original three books in the series. There are three more that were written at a later time, but I think it is time for me to move on to something else.

I found the series to be quite intriguing. Much of the plot was based on philosophical misdirection. This meant that each new chapter brought new information as well as new unknowns. This kept the plot alive in my mind and kept me thinking about what might happen next. I found this to be both good and bad. It was good because it made the story interesting. It was bad because I was focused on the plot and not of the messages and philosophy presented by the author.

Generally, when I read I am not worried about the story's plot. I enjoy pondering the information presented by the author much more. Reading this series, where both were present, created a real conflict as I read. In the end the plot was too much of a distraction and so I just quickly finished the book to feed my desire to know what was going to happen next. Thus I probably missed a lot of interesting information which was weaved into the story.

Because of the way the first book was constructed I had more time to think about what was being discussed in the book. I really enjoyed thinking about Asimov's ideas about the interaction between education, technology, religion, science, societal advancement and stagnation. It was interesting to think about where our current society stands in comparison to what he was describing.

I highly suggest the foundation series on many levels. The science fiction was great. The depth of the story was wonderful. The writing was clean and fun to read.

10 September 2009

Cascade Mountain Hike

Ever since we moved to Orem I have been looking at Cascade Mountain wanting to climb it. Every morning when I would step outside it stood there laughing at me. But no longer! This labor day I climbed to the summit and conquered the mountain. Yeah, it got a few good blows in against me too. My knees are still hurting a bit from the hike down.

Nate and I had been researching how to get to the top of this mountain for quite a while and we finally drove up Provo Canyon on a search for a good trailhead. After driving around for about an hour we finally came upon a marked trail at Big Springs Park. I didn't know this park existed until this drive. It is a nice little park set way back in the mountains. To get there you drive up Provo Canyon, exit at Vivian Park, and then follow Southfork Road a few miles until you reach Big Springs Park. At the back of the park is a trailhead marker stating that the Cascade Saddle is 4.1 miles up the trail. We now knew where to start. We just had to plan when. Labor Day became the answer to that question. So on Monday a party of 5 set off on the trail at 6:00 AM.

It is still dark outside at 6:00 AM. The first 30-40 minutes we hiked following a single headlamp. Luckily the trail is very clean and nice. In fact, the trail was a lot nicer than I had expected. All the way to the saddle the trail was well defined, not to steep, somewhat shaded, and just a nice walk. By the time we got to the top of the saddle we were wondering what happened to our challenging hike. This was really easy and we thought we were almost there. We were not disappointed though, the hike turned out to be quite challenging and we were not almost there.

From the saddle the trail continued down the other side of the mountain as the Dry Creek Trail but it did not continue on to Cascade Peak. Only the ridge of the mountain continued toward the peak. The trail along the ridge quickly narrowed and much of the ground turned to loose scree. We thought the peek was not too far from where we stood on the saddle, but it turned out it was hiding behind another set of lower peeks. We ended up having another 3 miles to hike.

Several things combined to make the hike along the ridge somewhat technically challenging. You had to be careful where to step due to the loose rock. Several times the ridge was very narrow and large trees were growing right on the top of the ridge. This situation required that you either climb over tree branches or walk down below the ridge. At some points the one side of the ridge was a sheer cliff. The other side was still passable but it certainly limited the trail possibilities. There were several peaks that we climbed before reaching the true summit. Between each peak was a valley in the ridge. This meant that we climbed up and then down several peaks making the hike long and hard. On the return trip we did not follow the ridgeline much at all. We instead hiked on the South side of the mountain 100 feet or so below the ridge. The side of the mountain was steep and covered with scree, but it was easier than the constant rise and fall in elevation.

We made it to the summit right about noon. A full 6 hours after we started. The view was spectacular.

By the time we arrived at the summit I was starving. I sat down, ate lunch, rested. Knowing we had a long hike back down the mountain we stayed just long enough to take a few pictures and sign the register. Overall, this was a great hike. I was better prepared than I was for last years Mt. Nebo hike. It was still quite painful coming down the mountain, but going up was great. I recommend the hike to anyone with a full day available and a fair amount of experience under their belt.

23 August 2009

Big Baldy - One Year Later

I climbed Big Baldy again. You can read about my first venture up baldy if you haven't taken that opportunity yet. So, I have been exercising quite a bit since my last trip up the mountain. I didn't think it was doing any good but after this trip I think it may be helping after all.

I started up the mountain Monday morning at 5:30 am. It was still dark outside so I wore a headlamp. The weather was beautiful. The trail is worn enough that it was pretty easy to follow in the dark. There were points, though, were the grass had grown so long on the side of the trail that it bent over and made the trail impossible to see. Luckily, at those points the trail was worn down into a rut which allowed me to stay on the trail by feel instead of by sight. It became light enough to see without the headlamp about 6:10.

I still had to go to work after the hike so I gave myself a time limit of 7:00 at which point I required myself to turn around and return home. At 6:30 I was at the top of the steepest grade and on the back side of the mountain. At this point, I knew I was close to the top. I sped up my pace to make sure I made it to the top before the 7:00 cut off time. I ended up jogging about a half mile of the trail. I finally reached the summit at exactly 7:00 with at least 15 seconds to spare. I climb the trail in only an hour and a half this year cutting about an hour off of last year's time.

After a brief stop to catch my breath I headed back down the mountain. As I headed down I noticed the same birds that I saw last year at the top of the mountain. I got a better look this time at what they were. It was a bunch of grouse running around.

The trip down the mountain took almost as long to make as the trip up the mountain. It was so steep that I had to travel pretty slowly on large parts of the trail. But I made it home at last with just enough time the take a quick shower and run off to work. What a great way to start the work week.

17 July 2009

PHPUnit Custom Extension - Class ... could not be found in ...

(For the impatient, include your class early, that is the solution.)

So I have been using PHPUnit for quite some time now and find that it is a great library for testing. I also find that testing really helps in development. I also find that PHPUnit can be infuriating to use at times. For instance, I wanted to create a new base class that extendeds PHPUnit_Framework_TestCase so I can add some custom logging or something like that to all of my tests. So I simply create,
class lib_MyBaseUnitTest extends PHPUnit_Framework_TestCase {
    ....
}
Then I create my test cases,
class tests_MyFirstTest extends lib_MyBaseUnitTest {
    ....
}
Now whenever I run
phpunit tests/MyFirstTest.php
 I get the error:
Class lib_MyBaseUnitTest could not be found in tests/MyFirstTest.php
So clearly from the error the base class in not being loaded...? Actually, the problem is that the base class is being loaded by the autoloader when phpunit tries to load the test and the base class gets in the way. The phpunit code that causes the problem is located in StandardTestSuiteLoader.php.
PHPUnit_Util_Class::collectStart();
PHPUnit_Util_Fileloader::checkAndLoad($suiteClassFile, $syntaxCheck);
$loadedClasses = PHPUnit_Util_Class::collectEnd();
The collectStart call gathers the list of loaded classes and stores them in memory. The checkAndLoad call then includes each of the files listed in your suite, or the file specified on the commandline, thus loading more classes into memory. The collectEnd call now gathers the new list of loaded classes and diffs the result with the list collected in the collectStart call. Each of the resulting classes should be a test case that needs to be run. The problem is that the autoloader loaded both the specified test case and its base class. When PHPUnit tests to see if it can run the base class as a test, it can't and therefore throws and exception, "Class ... can not be found in ...".

So the solution in the end that I have taken is to place require_once calls in my bootstrap file for all custom base classes. This way the class will be in the initial list of classes created by the collectStart call. It will not be in the $loadedClasses variable and therefore will not cause an exception to be thrown.

22 June 2009

Bearpaw Lake

I spent the last week in the Grand Teton Nation Park. It has been said that the Park is the Disneyland of the National Park system. This seemed to be accurate as there was fun to be had by myself, my wife and my young children. Everyone had a good time. While I did a lot of different things from riding in a covered wagon and watching an old west shoot out to white water rafting I will focus this post only on my hike to Bearpaw Lake.

Bearpaw Lake is the oblong blue spot on the map just north of Leigh Lake. I rode the ferry across Jenny Lake from the South Visitors Center to the Hidden Falls trail head. From there I followed the trail on the west side of Jenny Lake to the trail on the east side of String Lake and Leigh Lake and then up to Bearpaw Lake. I completed my hike at Jenny Lake Lodge.

The overall trip was about 10 miles. The trail was fairly flat and well maintained allowing for fast and easy hiking. The landscapes were beautiful and the lakes pristine. Wildlife was abundant, especially the mosquitoes. I almost ran over a bull moose eating the vegetation on the edge of the trail. He didn't seem to mind me being there at all, which I appreciated. I saw eagles soaring above me. I also saw a lot of humans.

I found it interesting to see how well maintained everything was. As I hiked I heard a chain saw cutting through some fallen trees. Evidence of this could be seen quite often along the trail. Campsites were organized and bear safe lockers were available at each site. Flags and markers were frequent to give direction and show detours. I was surprised at how unnaturally this part of nature was being preserved.

Overall this hike was very beautiful and enjoyable. Next time I am in the area though I will hike deeper into the mountains hoping for a more natural experience.

28 April 2009

Gawayne and the Green Knight

I finished another good story recently. This story I listened to instead of read. During my morning workouts I have started listening to stories because, as far as I can tell, either cable providers are completely disconnected to their audience or I am not their audience. Sixty channels of trash was too much for me so now I do my best not to look at the filth on the screen at the gym and focus on a good story instead. I find the stories I listen to on the Librivox website.

Gawayne and the Green Knight is the story Sir Gawayne, a knight of King Aurthur's court. It is a short story written as an old english rhyme in the late 14th-century. I read the modern adaptation by Charlton Miner Lewis. It was a fun story with all the joys of Arthurian legend. There were knights, damsels, and of course a quest. The story was fun and enjoyable to read.

At one point where Sir Gawayne's virtue is tested to the utmost he states the following:
Love? What is love? Not the wild feverish thrill,
When heart to heart the thronging pulses fill,
And lips that close in parching kisses find
No speech but those;--the best remains behind.
The tranquil spirit--the divine assurance
That this life's seemings have a high endurance--
Thoughts that allay this restless striving, calm
The passionate heart, and fill old wounds with balm;--
These are the choirs invisible that move
In white processionals up the aisles of love.
He strikes a point that has been largely forgotten in the world today. Love is deeper than infatuation. Love is more enduring than passion. In our world of quick fixes and fast satisfaction love is being lost. Marriages end with the first disagreement. Families are broken by the unfocused lust for pleasure. There needs to be a return to love being that of healing wounds, calming fears, enduring both pain and pleasure. That is love.

12 February 2009

PHP Errors and Exceptions

I learned something about php error handling the other day. I was digging through the docs and discovered how to catch errors, warnings, and such and then re-throw them as exceptions. This is great because I already implemented a default exception handling and logging system to catch all exceptions. Now I can use the same routines for PHP errors. The keys to making this work are the set_error_handler function and the ErrorException class. The set_error_handler has been around for a long time, but I have never really used it. This is a failing on my part. The ErrorException class seems to have been made especially for this type of operation. The ErrorException documentation shows exactly how to use these two things together for object oriented goodness in PHP.
<?php
  function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
  }
  set_error_handler("exception_error_handler");
?>
The function name passed to set_error_handler will be called if there is ever a PHP error. The function set up to handle errors takes the error information, constructs an ErrorException and then throws it. Errors never go directly out to the user or logs, they are always wrapped in an exception. Doing this give you greater control over error handling.

In the user comments on the ErrorException page troelskn gives a suggestion for improvement to the basic example above. He suggests the following code.
<?php
function exception_error_handler($severity, $message, $filename, $lineno) {
  if (error_reporting() == 0) {
    return;
  }
  if (error_reporting() & $severity) {
    throw new ErrorException($message, 0, $severity, $filename, $lineno);
  }
}
set_error_handler('exception_error_handler');
?>
This code allows the error reporting value set in php.ini to effect the behavior of the exception_error_handler. Only errors of a high enough severity will be passed on as exceptions. Using his code, if you have warnings suppressed, they will not raise an exception. They will just not be reported. I hope this removes one more of the little PHP quarks for you.

08 February 2009

Extolling the virtues of wool

I can't say enough good things about wool. I have always been told that wool is great for winter camping, but have never really listened. I am now a convert. It all started a few weeks ago when I went to buy some running socks. My old cotton socks were rubbing my feet raw, so I stopped in at Runner's Corner knowing that they would have a good selection of socks. I picked up a couple of pairs of nice socks for running. Then it happened. I saw the wool socks. I remembered that I was going to go on a winter campout in a few weeks, so I looked at the options and picked up a pair of Feetures Bamboo & Wool hiking socks.

I love these socks. They are so comfortable. First off, they come is a size that fits me. The medium size fits shoes sizes 6-8.5. This is great for me because I am a size 8. They fit nice and tight, the way I like it. I don't know why most sock manufactures think that one sock can fit sizes 6-12. It's just silly. Second, the fabric feels great. It took just a little bit of getting used to. It has a different feel then anything I have ever worn. You can feel the fibers in the sock, but they are very soft and nice. Third, no sweat. I don't sweat in these socks. I walk to work most days and when there is a lot of snow on the ground I wear my hiking boots. This is great for the walk, but very hot for inside the building. I have a pair of sandals at work now, but for a while I just wore my boots all day. With my normal cotton socks, my feet were very hot and sweaty, but with these wool socks, no sweat! They help regulate the heat and keep my feet at a comfortable temperature in the heat and the cold. Fourth, they stay dry. I wore my low top hiking shoes with my new socks to work one day last week. It snowed about 4-5 inches that day during work hours. I hiked home through all that snow and then started shoveling the snow when I got home. The bottom of my jeans were soaked. I had snow packed around my ankle. I didn't even notice until I started to take my shoes off. I was completely dry. I shook the snow off my socks and they were still dry too. My conversion was complete.

I went camping this weekend in about a foot of snow. Because of my recent conversion, I went to the local thrift store and picked up a $6 pair of wool suit pants as opposed to the $140 pair of ski pants the salesman at the outfitters store tried to sell me. After tromping through the snow for two days, I was completely dry. Never wet once.

I love wool.

20 January 2009

The Strange Case of Dr. Jekyll and Mr. Hyde

Barnes & Noble recently had a sale on their own series of classic literature books so I bought a few. I started reading The Strange Case of Dr. Jekyll and Mr. Hyde by Robert Louis Stevenson and had a very hard time putting it down. I was very impressed at Mr. Stevenson's command of language. His word choice and composition made the book very enjoyable. It was quick to read but carried with it very full imagery.

The overall metaphor and discussion about the dual personality of man was rich. In my view he captured that struggle that everyone has as we live life. Without suggesting how we should act he was able to very powerfully describe how and why we act the way we do. I think this is a very effective way to teach, explain the way things are and what consequences there may be and let people choose for themselves.

As Dr. Jekyll wrote explaining what was happening to him, he used the word liberty a few times in his description of Mr. Hyde's behavior. I found this to be a very accurate description of peoples thinking, though, personally, I think it is a short sited mistake in their thinking. For example, Dr. Jekyll describes his feelings at the beginning of his experiment by saying, "I was the first that could plod in the public eye with a load of genial respectability, and in a moment, like a schoolboy, strip off these lendings and spring headlong into the sea of liberty." He felt that by shedding the respectable side of his person he was now more free to act in any way he wanted to. Later in his experiment he discovers that he likes the respectable side of his person better, but still states that his other side has more liberty. "Yes, I preferred the elderly and discontented doctor, surrounded by friends and cherishing honest hopes; and bade a resolute farewell to the liberty, the comparative youth, the light step, leaping impulses and secret pleasures, that I had enjoyed in the disguise of Hyde."

I think the overall story and life itself points to the fact that this definition of liberty is flawed. In the person of Dr. Jekyll he had the power to be either Jekyll or Hyde. But in the person of Mr. Hyde he lost all his freedom. He describes himself as by saying that "his terror of the gallows drove him continually to commit temporary suicide, and return to his subordinate station of a part instead of a person; but he loathed the necessity." Mr. Hyde began to appear even when Dr. Jekyll did not want him to and soon he could not be controlled at all. In the end he committed suicide showing that he had no liberty at all because he chose to live as Mr. Hyde.

Real life is the same in that as we chose good we gain more liberty not less. And as we choose poorly we lose our liberty; we become trapped and unhappy. We often look at behaviors displayed in the world and in the media thinking that we are trapped because we cannot act in that way. This is a misconception. We can act that way, but as Dr. Jekyll found out, it only looks like it would be liberating. In reality it may be exciting or pleasurable for a short time, but it will not bring lasting happiness, only misery.