MySQL 5.5, Mac OS X and startup item security error

A few days ago I got a shiny new macbook at work and I needed to install my dev environment again.

I came across a few problems when installing the new MySQL community server package though, which had been upgraded to 5.5 instead of the 5.1 release I had on my old Mac.

Fixing MySQL server startup

The first problem I came across was that the server would not start properly, using the prefpane item.

This is easily fixed by editing the file /usr/local/mysql/support-files/mysql.server and going to line 46 + 47 and replacing the lines there with this:

basedir=/usr/local/mysql
datadir=/usr/local/mysql/data

You can now use the prefpane item to start your MySQL server.

source: http://forums.mysql.com/read.php?11,399397,399606#msg-399606

Fixing the autostart

If you are like me, you like it when all the services start at boot, since you don’t have to start ’em by hand.
However, there is a problem with getting MySQL server 5.5 to start using the prefpane.

In order to get the autostart up and running you need to fix the privileges on the startup item.
Open a terminal and do the following:

sudo chown :wheel /Library/StartupItems/MySQLCOM/MySQLCOM 
sudo chown :wheel /Library/StartupItems/MySQLCOM/StartupParameters.plist

After that you need to restart the computer. Logging out and back ind will not do the job.

source: http://bugs.mysql.com/bug.php?id=57790#c350454

Rails plugin development using WebMock

I had a few problems getting WebMock working with my rails 3 setup.

When I used webmock in my rails 3 app, the tests ran and all was nice.
But when I wanted to create a plugin using the exact same code as I just tested inside my rails app, I went into some problems.

To start, I created a new plugin using

rails generate plugin myclient

The files were generated and all seemed fine.
I then wanted to use the webmock plugin, since my client relied on some external services. (Which a test really shouldn’t do)

I had a really simple test case, just to get started:

require 'test_helper'
require 'webmock/test_unit'
require 'curb'

class MyClientTest < ActiveSupport::TestCase
  # Replace this with your real tests.
  test "the truth" do
    assert true
  end
  
  test 'webmock testing' do
    WebMock.stub_request(:any, 'www.example.com').to_return(:body => 'tester')
    data = Curl::Easy.perform("www.example.com")
    p data.body_str
    assert data.body_str == 'tester'
  end
end

When I ran “rake test” the test failed and the body that was returned, was the body of the actual page at www.example.com.
After bashing at the problem for a long time, I found out, that webmock doesn’t work if webmock is required before curb.

So… This was just a note about something that really took up too much of my time, and… yes, I should have know that webmock couldn’t “overwrite” the curb methods, if it was loaded in first.

Anyways, the final code that works!

require 'test_helper'
require 'curb'
require 'webmock/test_unit'

class MyClientTest < ActiveSupport::TestCase
  # Replace this with your real tests.
  test "the truth" do
    assert true
  end
  
  test 'webmock testing' do
    WebMock.stub_request(:any, 'www.example.com').to_return(:body => 'tester')
    data = Curl::Easy.perform("www.example.com")
    p data.body_str
    assert data.body_str == 'tester'
  end
end

Read more, continue reading, and how to easily fix it using WP

Yesterday I updated my grayish blog theme to a new blue and white theme, with more whitespace and less constraints.
While the new theme is isn’t perfect, I shined my website up a bit and it seems nice.

However, scrolling through my twitter list today, I read a blog post by Karan over at mardahl.dk, where she discusses the usage of “Read more” and “Click here” links on webpages. (Direct link to the blog post here).

This made me investigate what my own website was doing, and while the wording was a bit different, I had the same usability problem she describes in the blog post (you should really read it). People tend to overlook the wording, since lots and lots of advertisements use it. So when I use excerpts on my blog front page, and use the wording “Continue reading”, I’m actually scaring the user off, because my message will be misunderstood.

How I fixed it

When I made my new theme, I simply copied the twentyten theme supplied with wordpress 3, gave it a new name, fixed the style.css file to have my details in it and started to change the stylesheet to make it fit what I wanted.

Karan suggests using a different wording on the links, so it has the “Read more” wording, but includes the title of what it actually is, you are reading about.

She suggests the following:

Read more about Education
Read more about our Picture Archive
Read more about meeting the museum around town

And that’s the approach I’m going to use as well. However, I will be using the wordpress wording of “Continue reading”, since it was there to begin with and because it sounds more like a continuation instead of a whole new beginning to me.

Another thing to consider is, that my blog post’s link will be auto generated, so it’s easier to do something a bit more generic.

This means, that I will be using the following convention:

Continue reading “my blog post title”

To do this using the twentyten theme, open up the functions.php file that you copied with the theme.

If this is the first time you are altering the file, simply go to line 240, else search for the function named: “twentyten_continue_reading_link()”.

The function is defined as follows:

/**
 * Returns a "Continue Reading" link for excerpts
 *
 * @since Twenty Ten 1.0
 * @return string "Continue Reading" link
 */
function twentyten_continue_reading_link() {
  return ' <a href="'. get_permalink() . '">' . __( 'Continue reading <span class="meta-nav">&rarr;</span>', 'twentyten' ) . '</a>';
}

After browsing a bit of documentation in the “original” functions.php that wordpress core provides, it seems using globals is that way to go, if you want access to the current post object.

This will make the code look like this:

function twentyten_continue_reading_link() {
  global $post;
  
  return ' <a href="'. get_permalink() . '">' . __( 'Continue reading <span class="meta-nav">&rarr;</span>', 'twentyten' ) . '</a>';
}

We now have access to the post object and can get the post title from the title from it.
This is done using the variable post_title from the $post object.

The finished code looks like this:

function twentyten_continue_reading_link() {
  global $post;
  
  return ' <div class="read_more"> '. __('Continue reading', 'twentyten') .' <a href="'. get_permalink() . '">"'. $post->post_title .'" &raquo;</a> </div>';
}

I added a div with a class of “read_more” around the link, so it would make it easier to style.

After the div there is the wording Continue reading and then the link to the blog post, using the title of the post.

What’s your approach ?

And do you agree with Karan that this will make it more usable or is it the same or even worse ?

All I can say is, that I have already changed it on my blog.

Windows clients with CUPS and Samba

After starting my new job, I battled a bit with getting a printer/scanner working on the local network.
The fileserver was a mess as well… a real mess.

My boss gave me permission to install linux on it (since I haven’t really used windows for a long time now) and fix the filesharing and printing on it.
I jumped into the task, knowing in the back of my head, that printing always is a bloody mess to fix, when you have WINDOWS clients on the network.

Anyways, without looking back, I grabbed the new Ubuntu 10.04 server and installed the system. Didn’t take long, not even for the old machine we have.

After the system was installed, I setup a shared folder and some user shares. I even added our printer (Some old HP CM1015 printer, with a scanner).
No worries!… well.. on my Mac at least.
The windows clients kept having problems connecting to the printer, but the file shares worked perfectly.

After 2 months of hearing complaints on and off, I finally did some more work with the server and found that this samba -> cups configuration works:

load printers = yes
printing = cups
printcap name = cups

[printers]
  browsable = yes
  printable = yes
  public = yes
  create mode = 0700
  guest ok = yes
  use client driver = yes
  guest account = smbprint
  path = /var/spool/samba

As you can see I added a guest account as well.

/usr/sbin/adduser --system --disabled-password smbprint

The printer can now be discovered on the network simply by choosing Networks->SERVER_NAME, the shared folders and printers are now displayed.
Just right click on the printer and choose connect.

A special thanks to this guide: http://tldp.org/HOWTO/Debian-and-Windows-Shared-Printing/sharing_with_windows.html

Making a Cafe Latté without a “do it all” machine

As you properly know, if you know me in real life, “I love coffee”.
(I also like tea though, but that’s a whole different story.)

Today when I wanted to make me a Latté, I thought to myself:
Why not tell other people how it’s done, so they also can enjoy a Cafe Latté without buying an expensive espresso machine.

What you need

For my Latté setup I use the following equipment:
1x Cooking pot
1x Whisk (google translated this one for me)
1x Coffee press
Some hot water
3x tea spoons of grinded coffe (roughly 14-21grams)
Half a cup of milk (I’m using light milk)
And 10 minutes to spare…

Here is a picture of the setup:
My setup
(Yep, lots of things to wash up afterwards…)

Ready, Set, GO!

First things first. Start by putting on a kettle of with water.
Then grind your coffee beans. (Freshly grinded is always best!)
Grinded coffee beans

Put the grinded coffee beans in the coffee press.
When the water is boiled, wait roughly 30seconds and pour it over the coffee beans.
Pouring hot water over beans

Set a timer between 3mins 30secs and 4minutes, to let the water get the taste of the grinded coffee beans.
Set a timer

And then we need to start making the Latté milk foam.
Since I don’t have any kind of steamer, i’m simply pouring half a cup of milk in the pot and whiskering it for the duration the coffee needs to “drag”. (The amount of time we set on the timer)

After the milk is done, it will look something like this (all puffy and nice):
Puffed milk

Fill the cup with half coffee and half milk.
I normally pour in the coffee first, then the milk on top. Remember to get lots of the puffed milk at the top, to give it that Cafe-like look.
Latte is done

Using form_tag and collection_select with Rails3

After being away from rails for a while, i’m coming back en version 3 to check it all out again.

I had a problem with how to create a simple select, using the FormHelper.

I had two models, a user and a customer. They are defined as follows:

class User < ActiveRecord::Base
  belongs_to :customer
end
class Customer < ActiveRecord::Base
  has_many :users
end

In my UserController I have an action called new, where I initialize a new user object and fetch all the customers from the database:

class UsersController < ApplicationController
  # Opens the new user view.
  def new 
    @user = User.new
    # fetches all the customers, ordered by their name
    @customers = Customer.order(:name)
  end
end

However, when I wanted to associate the new user and a customer I couldn't remember how this was done. Then I headed over to api.rubyonrails.com and found the FormHelper, which didn't help me much though...
Then I looked at the FormOptionsHelper, which has the method:
collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})

In order to use this in my view, I had the following code:

<% form_for @user do |f| %>
<ul>
  <li>
    <%= f.label :customer %>
    <!-- select element here!-->
  </li>
  <li>
    <%= f.label :name %>:
    <%= f.text_field :name %>
  </li>
  <li>
    <%= f.label :email %>:
    <%= f.text_field :email %>
  </li>
  <li>
    <%= f.submit %>
  </li>
</ul>
<% end %>

The method states that it needs an object, a method, a collection, value, text. This resulted in the first try:

<li>
  <%= f.label :customer %>
  <% f.collection_select :user, :customer_id, @customers, :id, :name %>
</li>

Which gave a nice error...

This worked however:

<li>
  <%= f.label :customer %>
  <%= f.collection_select :customer_id, @customers, :id, :name %>
</li>

Why?
Well the form_tag was being done on the user object already, so the first object could be skipped.

Hope you can use it!

Switching coffee and PHP testing

Whoa, long time since my last post.

Anyways, what has happened recently?

I’ve switched jobs and are now working at a small IR firm in Denmark, which is located on Amager.
We do webcasts / Quarterly reports for firms in Denmark.

Saying “We do” is a bit off though.
I don’t, that is. I help out if we are missing a technician, else i’m creating webapps to help the business complete daily tasks faster.

And how is that going?
Well, I’ve completed a few systems already, and within one month the first system was deployed to the wild. It was fun to create a whole new system, especially because I am on my own.
Roughly speaking, i’m the only developer there, so I don’t get a lot of sparing on the code i’m writing. Only the designs and the general “look and feel” of an app.
It’s fun, it’s different and I like the pace.

An other thing i’ve been working on, is moving the old and new sites to new virtualized servers.
I’ve been managing a few servers for the last 6 years, but not anything on this scale. But it’s fun. It takes a little time from the programming though, but after it’s configured, it mostly runs smoothly.

I developed an SSO system and deployed it to the wild a few months ago. So far i’ve only had minor problems with it, and all things are running great.

And yes, I code in PHP. It was by choice actually. On my last jobs I’ve coded Bash, Perl, C, C++, then Java and then Ruby on Rails and on the new job I was given a free choice.

So I chose PHP.

“Why?” you might ask, when there’s soo much hype about Ruby on Rails these past few years. Without starting a flame wall in the comments, let’s just say, that while Ruby is a beautiful language, I just couldn’t get accustomed to the Rails frame work. So many rules, so many conventions. So little time. (The testing was nice though.. but meh)
I might return to Rails someday, but for now, it’s PHP controlling the battle.

The webapps i’ve created at my new job are all created using my small github project called php-mvc-base, which basically is just a structure I use to get started on a PHP project. It gives me “nice urls”, but other than that, the rules are pretty basic.

The structure outlines as follows:

/app
/app/controllers
/app/models
/app/views
/public/images
/public/javascripts
/public/stylesheets

And all controllers (ofc) go in the app/controllers folder.
So let’s say, that we want a new controller at the URL http://localhost/my_projects/ there is basically two things that can be done:
* Create a folder in the app/controllers folder, called my_projects. Place an index.php file there, do the controller code.
* Create a my_projects.php file in the app/controllers folder. Do the controller code.
Both options give the same path.

Simple and clean (well, at least in my world. And I use the folder approach btw, if you wanted to know).

(You can find the project at http://github.com/jimmiw/php-mvc-base along with a simple example.)

I’ve also released a few javascripts to CodeCanyon and I’ve had a few purchases already. It’s nice knowing people can use your stuff. I mostly coded them because I had a problem they could solve, but releasing them there, made the code so much better. This was mostly due to the javascript approval team on CodeCanyon (Thanks Jeremy McPeak for the patience and help).

You can see my profile on CodeCanyon here: http://codecanyon.net/user/jimmiw

I’ve also taken over a small project with a designer friend of mine called Janus C.
The project is familielivet and is a danish page the centers around the family. It’s free to use and hopefully easy to understand and use for all ages.
I’ve not actually released any code to the system yet, but we a doing some design changes and a total rewrite of the codebase, and it will hopefully be released soon.

After switching from Ruby to PHP I missed the easy testing that Ruby offered. Thank god for phpunit btw, this lovely tool simply makes testing fun again. Be sure to check it out when you are writing tests for your webapps (As you should be!).

On an interesting side note, Rails offers the ease of different environments for you to use.
E.g. Test, Staging and Production.
I actually found a simple way of doing this with PHP as well, but it requires that you have access to the apache configuration files (which you at least have on your development machine).

Roughly speaking, all you need to do, is to add a variable to your apache config, and then use the $_SERVER variable in PHP to test what environment your are currently working on.
Nice and simple.
A small example is this (taken from my development machine):
Just add the following piece of code to the bottom of your httpd.conf file
SetEnv APPLICATION_ENV "development"

And in PHP you can do the following when initializing the database connection:

<?php
  // development machine
  if($_SERVER['APPLICATION_ENV'] == "development") {
    mysql_connect(HOST, USER, PASSWORD);
    mysql_select_db(DATABASENAME);
  }
  // add as many environments as you want
  // the ELSE part is used for production. On shared hosts you cannot edit the
  // httpd.conf file, so if nothing is set, assume it's Production ;)
  else {
    mysql_connect(PRODUCTION_HOST, PRODUCTION_USER, PRODUCTION_PASSWORD);
    mysql_select_db(PRODUCTION_DATABASENAME);
  }
?>

I have a “unit” environment as well, which I use when testing database models using phpunit tests. This makes it easier to wipe database tables when starting tests.

And I switched from black coffee to Lattes.
No idea why, but after drinking black coffee for about 10years, they suddenly seem a bit boring…

Cycle through history in linux/mac terminal

If you are like me, you often use the terminal for… well.. let’s face it, most things.
I cannot remember one day, when i’m not bashing the keys in the terminal, trying to find, script or copy my way out of things.

Often I need to do the same things more than once. This could be connecting to a server to configure something, run a script I made earlier to resize some images, some FFMPEG command that I used earlier…

Eventually you get tired from hitting the arrow up key, and some years ago I got introduced to the “reverse history search”.
This is a way to search through your recent history (history being commands you’ve used in the terminal).

Simply hit CTRL+R to start the search, and the terminal will now look like this:
(reverse-i-search)`':

When you start typing, it searches through the history of your terminal.

One thing that bothered me though, was that I could only get the most recent result, and arrow up/arrow down doesn’t search through the results.

Hitting CTRL+R again displays the next result, that has the same command.

Just wanted to share it, happy bash’ing

WPML, what is the current language?

While building a wordpress theme that has multilingual support, I needed to know what the current language was for fixing some static parts of my template.

After searching a bit on the WPML site, I found a code example where you are shown howto create your own language selector menu:
http://wpml.org/documentation/getting-started-guide/language-setup/custom-language-switcher/

I then wrote this function to get the current language of a site:

/** 
 * Function for getting the active language of the WPML plugin
 * @return the currently active language, defaulting to 'en'
 */
function getActiveLanguage() {
  // fetches the list of languages
  $languages = icl_get_languages('skip_missing=N&orderby=KEY&order=DIR');

  $activeLanguage = 'en';

  // runs through the languages of the system, finding the active language
  foreach($languages as $language) {
    // tests if the language is the active one
    if($language['active'] == 1) {
      $activeLanguage = $language['language_code'];
    }
  }

  return $activeLanguage;
}
?>

Just add this code to the theme’s functions.php file and you are ready to find the active language of your site!

Using link_to in rails with :confirm and :method

Every time i’m going to use the link_to method in rails, I always seem to get a lot of errors.

The documentation states:

link_to(name, options = {}, html_options = nil)
link_to(options = {}, html_options = nil) do
# name
end

URL to the rails docs: http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#M001597

And gives a list of options you can set. However, I always seem to have problems remembering the correct syntax if I want to use :confirm and :method.

After fiddling with it a bit, I found that the proper way of using is:

%lt%= link_to(
  t("Delete"), 
  {
    :action => "destroy",
    :id => some_id
  },
  :method => :delete,
  :confirm => t('Are you sure you want to delete it?')
) %>

My biggest problem was, that you do not need to add the controller.

Also, found a nice write up about this on Ryan’s Scraps blog (a bit old post, but still…)

Hope you can use the tip.