A Guide to Running Unit Test using PHPUnit on Yii Framework

Let me tell you something:

TDD doesn’t drive towards good design, it drives away towards bad design. If you know what good design is, the result is a better design – Nat Pryce

I want to share my experience in setting up unit test (and later integrate it in CI —Continuous Integration) on my development machine. Hope this will save your time, my fellow developers, without going through of all errors and warnings I was stuck with before.

Disclaimer
I’m not an expert on Yii even though I have years of experience in PHP. In fact, this is the first time I’m using Yii. In the real world where I live, work and play, I use CodeIgniter and CakePHP. In terms of TDD, I started using it almost 2 years ago (thanks to Yahoo!) and always using it in almost every projects including Android (Java) and Python.

FYI, I’m using MacBookPro with MAMP PRO (PHP 5.3.6) installed. It wouldn’t be too difficult for you if you use Linux since it’s a similar process. If you use Windows, well, then goodluck! ;)

Let’s get started.

Continue reading

Merge Sort: The Algorithm

This is it. The last time I wrote about Merge Sort was last night last week and now I will show you the fun.

So here’s the code I’ve written in 9 minutes 42 seconds (almost 10 minutes!) straight.

from random import randint

def sample_list(n, r):
    result = []
    for c in range(0, n):
        result.append(randint(0, r))

    return result

def merge(left, right):
    i, j = 0, 0

    result = []

    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            result.append(left[i])
            i += 1
        else:
            j += 1

    if i < len(left):
        result += left[i:]

    if j < len(right):
        result += right[j:]

    return result

def sort(mylist):
    if len(mylist) < 2:
        return mylist

    midlist = len(mylist) / 2
    left_list = mylist[:midlist]
    right_list = mylist[midlist:]

    left_list, right_list = sort(left_list), sort(right_list)
    return merge(left_list, right_list)

if __name__ == '__main__':
    l = sample_list(10, 1000)
    print 'Unsorted list'
    print l
    print '\nSorted list'
    sort(l)

Pretty easy, right? Let me know if you have any comments or questions!

The Beauty of Merge Sort

First or second year of Computer Science’s students should not be surprised with this as this is one of the main subjects that must be mastered in order to advance to the next year. This subject usually taught in parallel with another algorithm in a lecture called “Introduction to Algorithm” or “Data Structures and Algorithm” depending on your campus.

It’s been years since I’ve got this material from university and I always come back to this subject again and again. Merge sort is one of the basic sorting algorithm but I still amazed with the way it do the sorting. So I set this weekend to visit the material again plus adding some more information about the merge sort into my head that once I’ve never known before (I’m not a nerd while back at the university so I don’t ‘eat’ everything my lecturer gave to me).

Let’s start with the easy one.

Continue reading

My First Day with Pebble and Why I Like It

It all began with a post from Kickstarter.

I’m really obsessed with technologies that can be customized and potentially useful in the future such as Google Glass, Android and so on. If some technologies come up and it says that I can create apps on top of it or it can be customized with coding, I definitely want to try it. So I decided to bought Pebble.

It doesn’t take too long for the shipping to be arrived (between 2 to 3 weeks). By the time I received the package, I opened it up and wore it on my wrist. It fits my wrist and really comfortable. I wore it for a whole day, reading the developer’s documentation, trying to make a simple ‘Hello World’ and reading specification on how to communicate with other devices using Bluetooth.

My simple conclusion is: I like it, and this is why I like Pebble.

Continue reading

10 Things That Make Cool Drivers, Cool

Driving is always my favorite activity since I was at high school. I never bored sitting behind the wheel and put my leg onto the gas pedal and push it hard. I used to be a (street) racer. I don’t mind running over 190kph using Mitsubishi Galant 2002 v6 2.4L on a Cikampek highway or running over 140kph using Honda Civic on a main road connecting Purworejo and Yogyakarta just to chase a BMW and a modified version of Corolla at 12AM and after that, running as fast as possible along with those cars as police chased us on the back (thank God I never get caught because I suddenly turned to the nearest gas station and hide while the police still chasing those two cars).

Jeez, those were my “dark ages” when I was young and now, as I’m become older, I always remind myself how important it is to be cool while driving.

“What.., wait! So you want to say that those 190kph thing-y and the pursuit wasn’t cool?”, someone asked me.

My answer when I was doing that: I felt pretty cool.

My answer recently until today and beyond: No.

Why? Simply because I have another definition of coolness while driving a car. Let me tell you.

Continue reading

Shannon’s Limit, Nyquist Limit, Bit Stuffing and Hamming Code

So, I’ve remembered that I was taking a network class while back at the university and now I am learning some of those things again and I want to share with all of you.

Why? Because I feel that I didn’t get much while back at the university and just before I go to sleep today, it all came back to me and suddenly I understand those things more than I was years ago.

So it’s about Shannon’s Limit, Nyquist Limit, Bit Stuffing and Hamming Code.

Attention:
To my frequent readers who are not familiar with the OSI layer, especially on Physical and Data-Link Layer, or non-technical person who always have some fun reading my posts, I need to notify you that the following post will be very technical and you can skip anytime you want. However, I’ll try as simple as possible to explain what I mean and probably you can get something from it. Just be sure that you’re okay with this and read ahead.

Let’s go with the first one. Shannon’s Limit (or Shannon’s Capacity). Continue reading

The Universality of APIs

The client should never ever decide how the server should response.

A few days ago, I was faced by the options to choose whether our API design should compromise its universality by changing the response in a non-standard format or stick with the original design. The need to change the API to the non-standard format came from one of its clients because they have some virtual restriction on how to process the response.

Let me explain that a little bit.

Recently, we have a project with one of telco companies here and we need to be able to open the API to talk to the SMS Gateway as well as IVR. We have defined a set of rules that should never be changed unless the end of the world is near. One of the API is a resource which can store the data into the database based on user’s SMS.

Let’s say that a user type these into their phone and send it as a text message to our server:

REGISTER John Doe#12345678#10-04-2002#Jakarta

and the user, John, will get a lot of information from the server like this:

Welcome, John Doe. It’s nice to meet you here and we welcome you to our brand new service. There are 102,452 people behind you waiting to access this service and can’t wait to join the new era of communication. Once again, congratulations on your joining today and here is your username along with a password. Username: johndoe. Password: johndoe123.

The backend will look something like this:

John Doe send a text message to a short number, 1234, and the phone will send it through MSC and SMSC. SMSC forward the packet to SMS Gateway and the SMS Gateway will forward the information to the server. The server’s response will be accepted by SMS Gateway and it will forward to the SMSC. SMSC to the MSC and finally, the user get the response from MSC. (Fiuh, what a confusing world we lived in).

So, why is it all related to the universality of APIs?

We discuss further on how to make a long response fit into user’s phone without even a single word being broken. As we’re already know, SMS is limited to 160 characters and we have the response exceeds this limitation, it will gonna break into two or more text messages. It’s fine. No problem with that.

The actual problem is that we don’t want to break even one word to be two pieces which became no meaning at all. Take as an example: welcome become wel come, communication become commun ication, and so on. This is not good.

So there comes the idea to break the long response into pieces and every pieces is no longer than 160 chars.

But how?

One of our team suggest that the server response would be something like this:

{
    'status': 'OK',
    'code': '200',
    'data': {
                   'response': 'register_ok',
                   'response_txt': 'Welcome, John Doe. It\'s nice to meet you
                       here and we welcome you to our brand new service.
                       There are 102,452 | people behind you waiting to access
                        this service and can\'t wait to join the new era
                        of communication. Once again, congratulations
                        on your joining | today and here is your username
                        along with a password. Username: johndoe.
                        Password: johndoe123.
                }
}

(If you noticed that I’m putting the pipe ‘|’ there, yes, you’re right. That is the separator for every 160 chars. Even though I didn’t put it exactly at the 160th char. This is just for illustration.)

This suggestion sounds very good and fix the problem. But be aware that this problem also break the API’s rule, universality (or in other term generality), and potentially create problems.

So what’s the problem?

So with the new API, the SMS Gateway is able to split the long response into pieces, each pieces has no longer than 160 chars. Everyone happy. The SMS Gateway is happy. The user is also happy (or maybe don’t care at all). But what about another third party app (such as Android or iOS client) that decided to use our API?

Yes, they have to split the response also. Or the proper way to do that is to strip the separator ‘|’ char from the response. But it’s not a proper way either. And suddenly, all third party clients questioning and complaining our API why in the world we always putting pipe in the middle of our response?

The Solution

The client should never ever decide how the server should response. We rolled back the API to the way it used to be –long response without the ugly pipe– and we suggest this simple function written in Python to solve the SMS Gateway problem:

def split_to_sms(txt):
    results = []
    txt_temp = txt

    while len(txt_temp) > 160:
        cut_pos = string.rfind(txt_temp, ' ', 0, 160)
        results.append(txt_temp[0 : cut_pos])
        txt_temp = txt_temp[cut_pos + 1 : ]

    if len(txt_temp) > 0:
        results.append(txt_temp)

    return results

We put the code in the client (SMS Gateway) and everybody is now really happy (the user still don’t care though, the response is much the same as before.)

Problem solved without compromising the API’s design principle.

Automate, Automate, Automate

As a programmer, I always encourage myself and others to be lazy.

No, I’m not kidding. Programmers should be lazy.

In my early days as a professional programmer, I worked like crazy. I like to do something manually. I like to type a command like javac happypuppy.java, java happypuppy.class and if there were errors, I also like to type setenv CLASSPATH ... happily. Manually. Without doubt.

When it comes to web development, I would zipped all the php files needed, sent it through ftp or scp (manually or by using tools like FileZilla or Cyberduck), unzipped it on the server side and opened the browser to test whether it’s worked on the server or was something broken there.

Building Android application was a little bit messy. I tested the code against my environment (and my emulator), I compiled and built the code manually using Eclipse and then take the individual apk file to be signed using command line. After that, I uploaded the apk to the server and let others to try. If bug was found, I would fix that bug on my local machine, re-compiled and re-built it using Eclipse. Take the individual apk file to be signed, uploaded the apk and let others to try again.

I might not realize that someday I would be terminated from this world knowing that the cause of my termination is an infinite loop. I hope not.

I learned very much in those process and I would never regret that I have ever been a ‘diligent’ programmer. I might not knowing anything if I just jumped over the process and using some tools that were just made to make my life easier. I might just said that I learned the hard way.

I started to understand the SVN and Git. I started to use bash script and Python script as much as possible. I started to learn Ant as part of Java build tools (you guessed it. It solely for Android). I started to get my feet wet with Hudson and Jenkins. I started to play with JUnit, Robotium, and Selenium. Bunch of tools I learned that makes me what I am today.

After all those things, I arrived at the conclusion that programmers should be lazy.

Reasons? Continue reading

Playing with Audio in HTML5

Recently, we had a little challenge on how to record our own voice using microphone with a very minimum effort from the user and store it in the cloud. What I mean with a minimum effort is that you don’t have to record your voice using a very great audio processing software such as GarageBand or Audacity and then manually uploading them to the cloud using ftp or scp (Windows people, please proceed and read the UNIX/Linux manual).

I know those steps are simple but I think we can handover the uploading process to the computer and let that machine do that for us. After all, our wish is their command. So I remember about the audio specification in HTML5 and decide to play with it. (By the way, I’m thinking of using Flash too, but I think you’ve already knew my answer. In fact, at the end of this article, I still leverage Flash ability to get the things done). Continue reading

2013, Year of Evolved Technology

You guess, yet another predictions for this year. 2013.

2012 was a very entertaining year if we talked about mobile. Android and iPhone are always side by side, one overtook another, to lead the market with their innovation and simplicity (and a ‘little’ fight on patent litigation). Nokia is not the number one anymore but they’re struggling to get the crown back by teaming up with Microsoft building Windows Phone on their Lumia series. BlackBerry considered no luck and very slow in launching their new shiny OS.

Almost every spotlight goes to mobile.

2013 is coming and this is the year where mobile become more and more adapted. A few players in mobile OS have been declaring them self to become ‘the next big thing’ in mobile field. Ubuntu, Tizen, Firefox OS and a few customized-based-on-Android devices ranging  from automobile industry to home automation expected to be exists no longer from now.

So, what is it all about in 2013? For me, it’s the year full of customized technology. It’s the year where mobile get the most attention and biggest penetration all over the world. Hence, customized technology will be seen as a new ‘toy’ and startups will move to this area, sooner or later.

These are 4 things that, in my prediction, will be the superstar (for one) and upcoming superstar (for others) of 2013: Continue reading