Posted on

Installing Apache on Mac OS X

Mac OS includes Apache and PHP, which is a bit handy for us developers. We all need a local environment and it helps if the local environment looks and feels a bit like the terminal ssh session we use to manage our production server. Configuration can be a little tricky however, and things change from version to version of the OS…

LAMP?

We’ll end up with a LAMP stack (more or less). LAMP is an acronym for:

  • Linux
  • Apache
  • MySQL (or MariaDB, MongoDB)
  • PHP (or Perl or Python)

Whilst Mac OS is not Linux, it’s Unix-based so it’ll do…

Steps

  • Check Apache
  • Enable PHP
  • Add virtual host configuration
  • Restart and check configuration
  • Install MySQL
  • Configure MySQL
  • Install additional tools

Check and Run Apache

Only run the start command if required…

$ ps aux | grep httpd

...
_www              431   0.0  0.0  2463684   1744   ??  S     8:23pm   0:00.00 /usr/sbin/httpd -D FOREGROUND
...

$ sudo apachectl start

Enable PHP

$ sudo vi /etc/apache2/httpd.conf

...
# Ensure this line is uncommented
LoadModule php5_module libexec/apache2/libphp5.so
...

Virtual Host Configuration

$ less /etc/apache2/users/myusername.conf

<VirtualHost *:80> 
        DocumentRoot "/Users/myusername/Sites" 
        ServerName myusername.local 
        ErrorLog "/private/var/log/apache2/myusername.local-error_log" 
        CustomLog "/private/var/log/apache2/myusername.local-access_log" common 

        <Directory "/Users/myusername/Sites"> 
                AllowOverride All 
                Order allow,deny 
                Allow from all 
        </Directory> 
</VirtualHost>

Check Your Work

Restarting Apache allows us to check this configuration is working. Create a directory “test” in /Users/myusername/Sites. Create a “hello world” index.html.

Restart Apache

$ sudo apachectl restart

Navigate to http://localhost/test/index.html. You should see your “hello world”.

403 Forbidden…

Argh! Pain! Apache runs under the _www user. This user needs to have 755 permissions to each directory in the heirarchy your site is located in. Chmod away…

$ chmod 755 /Users/myusername/Sites
$ chmod 755 /Users/myusername
$ etc...

Installing MySQL

MySQL is now distributed as a nice DMG package. Download it, install MySQL (open from the context menu if OSX complains about the legitimacy of the developer), and then install the preferences panel which adds MySQL to your preferences. Nip over to the shiny new settings pane and switch on MySQL. Check it out – it runs under a system user called mysql which has been available in MacOS installs for some time now.

$ ps aux | grep mysql
_mysql 1065 ... /usr/local/mysql/bin/mysql

Additional Tools

At least install a database admin tool locally. PHPMyAdmin does the job admirably – you’ll install it hosted in your new Apache PHP environment so there’s a nice circularity there… Alternatively use a MacOS database management application.

Posted on

Java: Pass by Value

Ever since I started coding in Java I’ve been regularly obliged to participate in conversations debating whether Java is a pass-by-value or pass-by-reference language. I’ve never been particularly hazy on the matter; Java is strictly a pass-by-value language and the values which are passed are pointers (to a memory location representing the data you are passing).

Lord knows there are enough articles online providing concrete examples of this fact. The one which I would recommend reading is here. Read the references too.

Posted on

Battling with Django Inheritance: Subclass Casting

For a day or so now I’ve been battling with Django’s model inheritance, which has a particularly frustrating approach to dynamic polymorphism.  The problem is that when one is implementing a group of related models using multi-table inheritance and you attempt to iterate over the bog standard QuerySet for the parent class, we see an unfortunate phenomenon: attributes and methods specific to a subclass will not be available as the list we are returned is a list of instances of the parent class, not the various children.

For example, I have a basic CMS which models a Page as having a series of Nuggets.  A Nugget could be a simple TextNugget, a TwitterNugget, a BlogNugget etc.  Each nugget has a title but beyond that each subclass must implement a method content() which returns the HTML content (including templatetags, in case you’re interested) which will be rendered by the browser in the appropriate place.  For ease of use I wish for my users to be able to select from available Nuggets without worrying about their type.

class Nugget(models.Model):
    title_text = models.CharField(_('Title'), max_length=200)
    show_title = models.BooleanField(_('Show'))
    text = models.TextField(_('Text'), blank=True)
    def __unicode__(self):
        return self.title

    def title(self):
        return self.title_text  

    def content(self):
        return self.text

# extends Nugget
class TwitterNugget(Nugget):
    username = models.CharField(_('username'), max_length=30)
    def __unicode__(self):
        return self.title

    def content(self):
        return "{% insert_tweets user" + self.username + "%}"

    def title(self):
        return self.title_text

In order to access, for example, the content method of a Nugget and be sure that we’re going to get the twitter templatetag, rather than the text which the inherited method would provide, we need to be sure that the iterator provided by the QuerySet is going to give us instances of the child (TwitterNugget) class, rather than instances of Nugget. In order to achieve this, we should override the Manager for the Nugget class to return a new kind of QuerySet – one with overriden __getitem__ and __iter__ methods which cast our models to the correct child classes. In turn this requires us to implement this new type of QuerySet (the PolymorphicQuerySet)

Determining which type of object should be returned in the iterator is done using a content_type field in the model – we have to override the save method on the Nugget to make sure that the content_type is written when we persist the model. content_type is a ForeignKey to the ContentType model provided in the django ContentTypes package.

from django.contrib.contenttypes.models import ContentType
from django.db.models.query import QuerySet

class PolymorphicQuerySet(QuerySet):
    def __getitem__(self, k):
        result = super(PolymorphicQuerySet, self).__getitem__(k)
        if isinstance(result, models.Model) :
            return result.as_child_class()
        else :
            return result
    def __iter__(self):
        for item in super(PolymorphicQuerySet, self).__iter__():
            yield item.as_child_class()

class NuggetManager(models.Manager):
    def get_query_set(self):
        return PolymorphicQuerySet(self.model)

class Nugget(models.Model):
    title_text = models.CharField(_('Title'), max_length=200)
    show_title = models.BooleanField(_('Show'))
    text = models.TextField(_('Text'), blank=True)

    content_type = 
    models.ForeignKey(ContentType,editable=False,null=True)
    objects = NuggetManager()

    def save(self, *args, **kwargs):
        if(not self.content_type):
            self.content_type = 
            ContentType.objects.get_for_model(self.__class__)
        super(Nugget, self).save(*args, **kwargs)

    def as_child_class(self):
        content_type = self.content_type
        model = content_type.model_class()
        if (model == Nugget):
            return self
        return model.objects.get(id=self.id)

    def __unicode__(self):
        return self.title

    def title(self):
        return self.title_text  

    def content(self):
        return self.text

# extends Nugget
class TwitterNugget(Nugget):
    username = models.CharField(_('username'), max_length=30)
    objects = NuggetManager()

    def __unicode__(self):
        return self.title

    def content(self):
        return "{% insert_tweets user" + self.username + "%}"

    def title(self):
        return self.title_text
Posted on

RIP eeePC 701

It is with great sadness that I inform you all that my Asus eeePC 701 has finally exhaled it’s last 7-inch breath, wheezing under the weight of the many superfluous processes running on it’s aging LinuxMint installation.  Please join me in thanking it for many years of service – it really did punch well above it’s weight.

Of course we shouldn’t dwell – enter the Asus eeePC R101.  One year on from the theft of the Gateway netbook I purchased in New York, this pocketable(-ish) wonder is riding on my back everywhere I go, allowing me to progress my pet projects in any downtime I might find.  It is no deluxe model, in fact it is as basic as they come, but it’s now dual booting Ubuntu Netbook (with Unity interface) and Windows 7.  I’ve been developing a client’s site (django) on it under the Ubuntu installation and it’s a joy to use.  I guess one benefit of spending years with a 7-inch screen and underpowered Celeron processor is that the bar is set low for subsequent purchases…

Posted on

Privacy rights and the standard of legal protection of these rights in the digital domain

This document was written as my submission for the computer science writing course I took in my third year of study at the University of York. It attempts to summarise the privacy issues associated with the development of new technologies in the information communications domain. Please don’t read with too much of a critical eye – it is old now and it was unfortunately a last minute effort, which I may one day improve.


Introduction

In order for one to consider the broad topic of ethics with regard to computer engineering, it is important to be sure that we understand precisely what “ethics” are. In her lecture notes, Susan Stepney defines ethics to be “right and wrong behaviour in a society” [1, p25], a definition expanded upon in Computer Ethics: “the code or set of principles by which people live” [2, p14]. These broad definitions suggest each of us have a good idea what is right and what is wrong, but a question central to the topic of this review is “can we judge the use of the Internet with existing ethical frameworks?” [1, p9]. Continue reading Privacy rights and the standard of legal protection of these rights in the digital domain