Drupal 7 clean URLs

I have today off from work, so I’ve been sitting around at home, messing with Drupal.
I couldn’t quite figure out how to get clean URLs to work, until I stumbled across this article. (See the “post-installation tips” section at the end.) Pretty simple really, and I should have been able to figure it out on my own, if I’d read as far as the RewriteBase section of the main clean URLs article on drupal.org.

I also went a bit nuts at www.packtpub.com today. They are running a special, 5 ebooks for $60, so I bought four Drupal books and one PHP book. I’m building up a bit of a library of ebooks that I’ve bought on sale, mostly from O’Reilly.  I never seem to have time to read them though!

Drupal 7

After staying out too late Tuesday night, then going to bed at 8:30pm last night, I finally had some free time after work tonight to play around with Drupal. I installed Drupal 7 on my MacBook, following these instructions. The only real trouble I had was in making sure that every host reference was set to 127.0.0.1 rather than localhost, or anything else.

Most of the obvious stuff seems to be working.  I haven’t figured out clean URLs yet though.

xAMP on the Mac

I’ve been trying to learn a bit about Drupal recently. It looks like we might be getting some Drupal projects at work, so it seemed like a good idea.

To get a working setup for Drupal on my Mac, I wanted to get all the pieces in place — Apache, PHP, and MySQL, basically. Apache is, of course, already there, and I already had that turned on, so no problem.

PHP was already installed, but apparently got turned off during the 10.7 upgrade. All you need to do to turn it on is edit httpd.conf, and uncomment one line, per this SO page.

For MySQL, there’s an installer that works pretty smoothly, per this page. One odd thing I stumbled across at one point is that you usually need to refer to your local server as ‘127.0.0.1’ rather than ‘localhost’. Long story, but something worth noting. Also, if you’re not sure how to set the root password, take a look at this SO page.

I tested to make sure that MySQL was working from PHP using this little test script:

<?php

$db = mysql_connect("127.0.0.1:3306", "root", "password");

if (!$db) {
    die('Could not connect' . mysql_error());
}
    echo 'Connected successfully';
?>

I can’t remember exactly where I found that, but it’s a pretty basic script.

I then got a little ambitious and decided to try to get phpMyAdmin working. I made a couple of simple mistakes here, including not quite understanding that config.inc.php needed to be in the root phpMyAdmin folder and not in the config subfolder.

Also, the warning from phpMyAdmin about mcrypt not being installed was bugging me, so I decided to try and fix that. That turned out to be kind of complicated. I followed these instructions, and they worked, but only on my second try. I must have gotten something wrong on the first try. Also, I found another page with similar instructions, so referencing that may help if anything on the first page seems confusing.

In the end, I think I really should have just gone with MAMP, but of course I was doing this as a learning exercise, so it was valuable to go through all this, even if it took a lot longer than was probably necessary.

And I still don’t have Drupal installed. Maybe tomorrow!

digital comics

I just spend $38 on $76 worth of digital comics from Dark Horse.  I had a 50% off coupon, good even on stuff that was already on sale. I now have nearly all the Hellboy and BPRD comics that came out since i stopped buying them regularly in 2009. Plus the first 16 issues of The Goon, which I’ve wanted to read, but never got around to buying. A little over 50 comics total.  Digital comics never seem worthwhile to me when they’re priced at close to the regular print cover price, but for less than $1 each, they’re not a bad deal.

fun with modal popups

At work, we frequently use the ModalPopupExtender from the Ajax Control Toolkit in our projects. I’ve got mixed feelings about this control, and about the ACT in general, but for better or worse, I do use it a lot. I discovered some functionality in the control this week that I was previously unaware of, so I thought I’d write up a blog entry on it, along with some related stuff that I stumbled across.

I needed to attach some JavaScript to the show and hide events for the popup, but wasn’t sure how to do that. It turns out that there are add_shown() and add_hiding() events that you can hook into, as described here. I initially found out about add_shown() at this StackOverflow page.

I then tried to hook up the event in the pageLoad() routine as shown in an example there. What I didn’t realize was that you can only have one pageLoad() function, and there was another one in a master page that was in my hierarchy, so my version didn’t get called. I then found out that I should change both of those to use Sys.Application.add_load() via this SO page.

Then, I followed up by learning a bit about the differences between pageLoad() and $(document).ready() at Encosia, which is one of the best sites out there for figuring out some of the trickier stuff when working with ASP.NET and JavaScript.

P.S. I just noticed that this is post # 1500 on my blog. There’s no real importance to that, but it’s always nice to hit a milestone.

Fractions!

I haven’t posted much code to my blog lately, so I thought I’d pass along some general-purpose C# code that I recently used in a project. I’m working on a system right now where the original author made some, shall we say, interesting decisions about how to store data in SQL. Specifically, he used varchar fields for most of the numeric data. And, in those fields, he sometimes stores the data in decimal format (e.g. “1.5”), sometimes as fractions (e.g. “1 1/2”) and sometimes as explicitly-signed fractions (“+1 1/2”).  I, of course, need to do LOTS of math on these numbers. The decimal fields can be dealt with using good old TryParse and ToString of course, but there’s no obvious parse routine for fractions, nor is there an obvious way to turn a decimal number back into a fraction string.

The internet, of course, provides. Here is a VB.NET function to turn a fraction string into a decimal and there is some C# code to convert a decimal into a fraction string in this thread. I converted the VB.NET to C#, and cleaned both of them up and put them in a utility class.  Here it is:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;

namespace MySuit.MySuitV2.BLL
{
    public class Utility
    {
        public static decimal FractionToDecimal(string frac)
        {
            // this method should convert a fraction, e.g. "12 1/4" to a decimal, e.g. 12.25.
            // based on http://amrelgarhytech.blogspot.com/2008/03/fraction-to-decimal.html
            // TODO: not sure how best to handle exceptions here. (parse errors, div by zero, null/empty string input...)
            decimal rv;
            int numerator, denominator, wholePart = 0;
            int sign = 1;

            if (string.IsNullOrEmpty(frac))
                return 0m;

            // deal with signs
            frac = frac.Trim().TrimStart('+');
            if (frac[0] == '-')
            {
                frac = frac.TrimStart('-');
                sign = -1;
            }
            frac = frac.Trim();

            if (frac.IndexOf("/") > 0)
            {
                if (frac.IndexOf(" ") > 0)
                {
                    wholePart = int.Parse(frac.Substring(0, frac.IndexOf(" ")));
                    frac = frac.Substring(frac.IndexOf(" "));
                }
                numerator = int.Parse(frac.Substring(0, frac.IndexOf("/")));
                denominator = int.Parse(frac.Substring(frac.IndexOf("/") + 1));
                rv = sign * (wholePart + ((decimal)numerator / denominator));
            }
            else
            {
                rv = decimal.Parse(frac);
            }
            return rv;
        }

        public static string DecimalToFractionSigned(decimal value)
        {
            // always put a sign (+/-) in front
            string rv = DecimalToFraction(value);
            if (rv[0] != '-')
                rv = string.Format("+{0}", rv);
            return rv;
        }

        public static string DecimalToFraction(decimal value)
        {
            // taken from here: http://bit.ly/tHaKrK and modified to work with negative numbers too.

            int sign = 1;
            if (value < 0)
            {
                value = Math.Abs(value);
                sign = -1;
            }

            // get the whole value of the fraction
            decimal mWhole = Math.Truncate(value);

            // get the fractional value
            decimal mFraction = value - mWhole;

            // initialize a numerator and denominator
            uint mNumerator = 0;
            uint mDenominator = 1;

            // ensure that there is actually a fraction
            if (mFraction > 0m)
            {
                // convert the value to a string so that you can count the number of decimal places there are
                string strFraction = mFraction.ToString().Remove(0, 2);

                // store the number of decimal places
                uint intFractLength = (uint)strFraction.Length;

                // set the numerator to have the proper amount of zeros
                mNumerator = (uint)Math.Pow(10, intFractLength);

                // parse the fraction value to an integer that equals [fraction value] * 10^[number of decimal places]
                uint.TryParse(strFraction, out mDenominator);

                // get the greatest common divisor for both numbers
                uint gcd = GreatestCommonDivisor(mDenominator, mNumerator);

                // divide the numerator and the denominator by the greatest common divisor
                mNumerator = mNumerator / gcd;
                mDenominator = mDenominator / gcd;
            }

            // create a string builder
            StringBuilder mBuilder = new StringBuilder();

            // add the whole number if it's greater than 0
            if (mWhole > 0m)
            {
                mBuilder.Append(mWhole);
            }

            // add the fraction if it's greater than 0m
            if (mFraction > 0m)
            {
                if (mBuilder.Length > 0)
                {
                    mBuilder.Append(" ");
                }

                mBuilder.Append(mDenominator);
                mBuilder.Append("/");
                mBuilder.Append(mNumerator);
            }

            if (sign == -1)
                mBuilder.Insert(0, '-');

            return mBuilder.ToString();
        }


        private static uint GreatestCommonDivisor(uint valA, uint valB)
        {
            // return 0 if both values are 0 (no GSD)
            if (valA == 0 && valB == 0)
            {
                return 0;
            }
            // return value b if only a == 0
            else if (valA == 0 && valB != 0)
            {
                return valB;
            }
            // return value a if only b == 0
            else if (valA != 0 && valB == 0)
            {
                return valA;
            }
            // actually find the GSD
            else
            {
                uint first = valA;
                uint second = valB;

                while (first != second)
                {
                    if (first > second)
                    {
                        first = first - second;
                    }
                    else
                    {
                        second = second - first;
                    }
                }

                return first;
            }
        }

    }
}

(This is also in a Gist.)
I hope this helps anyone who might be looking for something similar. Also, I want to reiterate that I didn’t write this code from scratch. I took two existing functions, one in VB and one in C#, converted the VB to C#, cleaned them both up a bit, and put them together.

Luckily, by the way, all of the fractions I’m dealing with resolve to simple decimal numbers; everything is x/2, x/4, or x/8. I don’t have to deal with converting 1/3 to decimal and back. If you need to do that, you probably want a class that stores the fractions as numerator and denominator, and does math on them, as fractions.  There are a couple of those out there, if you look around.

Steve Jobs – 1985

I recently finished reading a long interview with Steve Jobs that was published in Playboy back in 1985. You can find a text version of it here or read it at Playboy.com here. Some of the stuff in the interview is kind of funny, in retrospect. Some other stuff is a little heartbreaking, for obvious reasons. My favorite part of the interview is when they started talking about the future of computing:

PLAYBOY: What will change?

JOBS: The most compelling reason for most people to buy a computer for the home will be to link it into a nationwide communications network. We’re just in the beginning stages of what will be a truly remarkable breakthrough for most people—as remarkable as the telephone.

PLAYBOY: Specifically, what kind of breakthrough are you talking about?

JOBS: I can only begin to speculate. We see that a lot in our industry: You don’t know exactly what’s going to result, but you know it’s something very big and very good.

PLAYBOY: Then for now, aren’t you asking home-computer buyers to invest $3000 in what is essentially an act of faith?

JOBS: In the future, it won’t be an act of faith. The hard part of what we’re up against now is that people ask you about specifics and you can’t tell them. A hundred years ago, if somebody had asked Alexander Graham Bell, “What are you going to be able to do with a telephone?” he wouldn’t have been able to tell him the ways the telephone would affect the world. He didn’t know that people would use the telephone to call up and find out what movies were playing that night or to order some groceries or call a relative on the other side of the globe. But remember that first the public telegraph was inaugurated, in 1844. It was an amazing breakthrough in communications. You could actually send messages from New York to San Francisco in an afternoon. People talked about putting a telegraph on every desk in America to improve productivity. But it wouldn’t have worked. It required that people learn this whole sequence of strange incantations, Morse code, dots and dashes, to use the telegraph. It took about 40 hours to learn. The majority of people would never learn how to use it. So, fortunately, in the 1870s, Bell filed the patents for the telephone. It performed basically the same function as the telegraph, but people already knew how to use it. Also, the neatest thing about it was that besides allowing you to communicate with just words, it allowed you to sing.

iOS programming

I’m more than half-way through my iOS programming class at NYU. I’ve missed one class due to a flat tire, and I’ve been a bit under the weather during a couple of classes, but I’m definitely getting something out of the class.
I’ve made a Hypotrochoid generator the basis for my previous two homework assignments, so that’s been kind of fun. I didn’t figure out the code for this myself. Rather, I took the C# code found here, and converted it to Objective-C / Cocoa.
All of my homework code is up on my Github page, if anyone wants to look at it for some reason.
And here’s a quick screencast of my app. Not that exciting really, but fun to write.