Sunday, September 21, 2014

Discovering AngularJS

I've recently been pointed towards AngularJS by a mentor. At work, we typically use BackboneJS for our client-side framework needs. Since Backbone is so minimalist, over the past few years we've learned some (sometimes expensive) lessons and developed a set of best practices that minimize the pain of developing with Backbone.

The first thing I noticed when looking at Angular was how many of those implicit lessons and best practices become unnecessary! For example, it's not unusual for me to have to reimplement two-way binding for every application, and I've seen some complex mechanisms to do as-you-type filtering of a list. With Angular, it's so incredibly easy!

For example:

    <body>
        <div class="container" data-ng-controller="SomeController">
           
            <h3>Controllers</h3>
            Name: <input type="text" data-ng-model="nameFilter" />
            <ul>
                <li data-ng-repeat="person in people | filter:nameFilter">
                    {{person.name | uppercase}} loves {{person.city | uppercase}}
                </li>

            </ul>
        </div>
       
        <script type="text/javascript" src="js/libs/angular.min.js"></script>
        <script type="text/javascript" src="js/viewcontrollerscope.js"></script>
    </body>


And in the JS:

var demoApp = angular.module("demoApp", []);

var controllers = {};

controllers.SomeController =  function ($scope) {
    $scope.people = [
        { name: "Kim", city: "Green Bay" },
        { name: "Ron", city: "Miami" },
        { name: "Rufus", city: "Houston" },
        { name: "Wade", city: "San Francisco" }
    ];
};

demoApp.controller(controllers);



Boom! That's it. Most of that code is just boilerplate required to setup Angular itself, and one you do that, the filtering mechanism is handled within the bolded part of HTML template. Isn't that incredible?

I think I'm a little biased against Backbone because it was my first JS framework, and so the learning curve was obviously higher. However, I have to acknowledge, that Backbone is incredibly useful for adding small, clientside-driven pieces to an application. As far as I can tell, Angular seems much better oriented towards writing applications that are entirely clientside, single-page applications.

I highly recommend this tutorial for learning Angular. I found it incredibly useful. Let me know if you have any recommendations for Angular-related resources!


Wednesday, September 17, 2014

The Power of Habit - Willpower

I'm about halfway through The Power of Habit by Charles Duhigg now, and ever since his note on Keystone Habits, the book has been dragging on for a bit. I'm going to ignore his ramblings on organizational change and focus on the part that stood out to me the most in my reading today: his commentary on willpower and its role in habit formation.

I learned somewhere in High School the analogy that willpower is a finite resource. The more you use it, the more it gets depleted. Somehow, I feel like I internalized this in such a way that because willpower is a scarce resource, it should be conserved to be used when important. For example, I considered it okay to binge on snacks and junk food during exam-time when I had to use my willpower to focus on studying.

The Power of Habit likens willpower to be more like a muscle. The more you use it, he claims, the stronger it gets. This analogy is interesting because if it's more accurate than my idea of a finite resource, then my attitude towards willpower is like that of a man who is afraid that he might need to run someday, so he conserves his ability to run by never running. Of course, muscles being what they are, such a man would soon not be able to run very far at all.

The Power of Habit's suggestion (I had to weave through a good one-sixth of the book before I was able to distill it out) is that we can improve willpower by pre-planning our habits. So for instance, if you would like to get into the habit of ironing your clothes for the next day when you get home from work today, you should visualize in the morning how you're going to feel when you get home, how tired you'll be, and how you'll overcome that tiredness to power through and iron your clothes.

Another way of looking at it is that you would be "priming" yourself into making falling into the routine of ironing your clothes easier.

Here's what you can do: think of a habit you want to develop. It might be ironing your clothes at a certain time, or writing a blog post before bed, or cooking dinner instead of eating out. Visualize the crux moment when you usually give into temptation and ignore the task/chore you need to do and imagine yourself overcoming it. Do this everyday in the morning and hold on to it until you are able to develop the habit.

Here's the affiliate link to The Power of Habit if you'd like to support my blog. And here's the non-affiliate link if you're not into that. :)
The Power of Habit by Charles Duhigg

Tuesday, September 16, 2014

The Power of Habit - Keystone Habits

Continuing my reading today of The Power of Habit by Charles Duhigg, I came across The Power of Habit's concept of "Keystone Habits." He presents this, in particular, in the context of organizational change - changing one key habit can spiral into other changes that blossom into large-scale shifts in the organization in question, but suggests that it can be applied on the individual level as well.

The man The Power of Habit uses to present this idea is Paul O'Niell. O'Niell was the CEO of the aluminium manufacturing company Alcoa, and when he came in, Alcoa wasn't doing very well. There was a great deal of friction between management and unions, competitors were stealing business, and morale was low amongst employees.

O'Niell, The Power of Habit says, understood the power of keystone habits (it's funny how often these self-help books explain successful person X as understanding attribute Y of the framework they're presenting). He decided to focus on the keystone habit of "safety" and focusing on this habit improved operations all over Alcoa, and helped make the company ridiculously successful over O'Niell's tenure.

This in itself made me pause for a bit. While O'Niell's success in undeniable, is safety something you can call a habit? I would call it more of a priority, or a value, as opposed to a habit. Additionally, The Power of Habit fails to recognize what focusing on safety truly was for O'Niell - it was a political master-stroke. Faced with an environment fraught with labour-management tensions, safety was the banner everyone would have to rally behind, or else they would be painted as black sheep. What union leader, or manager would dare oppose an action justified in the name of safety?

The icing on the cake for this portion of the book though, was a passage in which The Power of Habit describes how, during his tenure on some government job, The Power of Habit was trying to solve the problem of child mortality, and he traces the root cause of the problem from child mortality to child malnutrition to the child's mother's malnutrition during pregnancy to the mother's education to the mother's teachers to those teachers' college education in nutrition and biology. This is where, The Power of Habit says, O'Niell attacked the problem. And then right at the end of the passage, he tacks on, “Today, the U.S. infant mortality rate is 68 percent lower than when O’Neill started the job.”

Like, really? You're going to tell me (or at least heavily imply) that just because O'Niell recommended changing a few curricula, the US has less infant mortality today? There's absolutely no support of this claim, and it's a basic correlation-causation error any Psych 101 student can spot. The Power of Habit lost a lot of credibility in my eyes with that claim, and this Daily Beast article suggests O'Niell himself disavowed himself from that statement.

That said, I do find the idea of keystone habits on an individual level interesting. It related with a concept I read in Switch: How to Change Things When Change Is Hard about how, when attempting to change, we should take a single, actionable item, and focus on that. Once that change is achieved, it provides the momentum to create a ripple effect that causes other, hopefully positive changes.


To this effect, I'm personally trying to cultivate in myself the habit of writing more often. I'm hoping that developing this will be a keystone habit will have a spillover effect by improving my communication skills, comprehension and whatnot. I don't think it will reduce the infant mortality rate of the US by two-thirds, but then again, not all of us can be Paul O'Niell.

Here's the an affiliate link to The Power of Habit if you'd like to support my blog. And here's the non-affiliate link if you're not into that. :)
The Power of Habit by Charles Duhigg

Monday, September 15, 2014

The Power of Habit - the Habit Loop

The Power of Habit by Charles Duhigg is a book I picked up recently from my local library. At about 25% in, it's already had a decent impact on my worldview, and I think it promises to be a good read. For this blog post, I want to write about the model The Power of Habit presents of habits.

The Power of Habit by Charles Duhigg 

First of all, habits are relatively simple things. It's when hundreds, even thousands of these coalesce around a single individual do they emerge as something as complex as the "lifestyle" of that individual.

Habits come from a three-step loop, says The Power of Habit. The first step of the loop is the "cue". This is what triggers the automatic behaviour, letting you relinquish your cognitive control. Since our brain is evolutionarily programmed to exert as little effort as possible, it is constantly on the outlook to set such "cues" that allow it to revert to default behaviour, and hence save you from expending too much brainpower.

The next step in the loop is the actual action that gets triggered.

The final step is the reward - this, says The Power of Habit, is what tells the brain whether the action it just took should be repeatable or not. The higher the reward, the more likely your brain is to want to engage in that behaviour again.

The Power of Habit uses the example of brushing teeth in his book. Back in World War One, he says, bad dental hygiene was on the verge of becoming a national crisis. In those days, hardly anyone brushed their teeth. Toothpastes and brushes for hygiene were regarded as the proverbial snake-oil. However, after an ingenious marketing campaign by a man called Claude Hopkins, by the time World War Two rolled around, it was discovered that nearly half the men in the Army were brushing their teeth regularly!

Hopkins worked his magic by associating a behaviour with a cue, and a reward the with behaviour. In this case, he used the filmy coating that we can feel on our teeth as a "cue". The behaviour he encouraged people to do was brush their teeth using the toothpaste he was marketing (a brand called Pepsodent), and the reward they got for it was a minty freshness from the toothpaste.

The Power of Habit notes that the minty freshness that we now associate with a clean mouth was a relatively new phenomenon back then, and that it has no effect on actual oral hygiene. In fact, many leading dentists of the day disclaimed Pepsodent as a farce, because it so heavily advertised the feeling of freshness. However, Pepsodent succeeded where so many other toothpaste brands failed because it gave its buyers a tangible reward (minty freshness) as opposed to a promise of good oral hygiene.

So there you have it - that's the Habit loop. Cue, behaviour, reward. This sequence evolved into a habit when it's repeated enough times so that through classical conditioning the brain starts anticipating the reward as soon as it sees the cue. This elicits an automatic craving that can't be satisfied until the behaviour is performed.

Here's the an affiliate link The Power of Habit if you'd like to support my blog. And here's the non-affiliate link if you're not into that. :)
The Power of Habit by Charles Duhigg

Sunday, September 14, 2014

Modifying the DigitalOcean django one-click project to use a custom directory

Hi all,

I recently gave DigitalOcean a shot on the recommendation of someone at HackerNews. DigitalOcean has a lot of custom droplets, which are basically Virtual Machines, that you can use to set up a cloud server on which to host your website.

I had been building a Django website that I wanted to put up, and while setting it up on DigitalOcean, I ran into the following problem: The default Django droplet uses a base Django project located in the 'home' directory of the UNIX installation DigitalOcean sets up for you. I wanted it to point to a custom directory in the /opt folder that I had set up.

In order to do this, remote into the DigitalOcean droplet. Once there, run the following command:

    sudo nano /etc/init/gunicorn.conf

In this file, change 'chdir /home/django' to point to the directory that contains your django project. In my case, I changed it to '/opt/venv'.

Change the 'name' field to refer to the folder that contains your 'wsgi' file. In my case, I changed it to 'name=jobs'.

Change the 'pythonpath' field to refer to folder that contains your 'manage.py' file. In my case, I changed it to 'pythonpath=search-jobs'.

In 'django_project.wsgi:application' change 'django_project' to the name of your Django app (ie. what you changed your 'name' field to).

Now run the following command:

    sudo nano /etc/nginx/sites-enabled/django

In this file, change the media and static locations to point to where you need them to point to. In my case I changed:

    alias /home/django/django_project/django_project/media;

to:

    alias /opt/venv/search-jobs/media;

and:

    alias /home/django/django_project/django_project/static;

to:

    alias /opt/venv/search-federal-jobs/staticfiles;


That should set up the default nginx and gunicorn to serve your django project located in your custom path properly!

If you have any feedback on this post, or if it helped, drop me a comment and let me know.

Tuesday, March 11, 2014

Lessons from a salesperson

Today, I reached out to my buddy Mike at work, asking him if he had could give me his perspective on what it means to be a salesperson. He readily agreed, and I jotted down some notes from my conversation with him which I am compiling here -

Know who you're talking to

Different people in an organization have different concerns and different pain points. What's important is that you contextualize your product/service in terms of the person or people you are talking to. 

For example - let's say you have developed a fancy new CMS that is a dozen times better than Company X's old Wordpress site. However, you can't walk into a presentation to the Marketing department of Company X and excitedly tell them how scalable and maintainable it is - they won't care. You need to tell the Marketing people how easy it is to update content and apply branding, just as you need to show off scalability and maintainability to the IT people.

For the various people working different roles, you're going to want to know beforehand what their pain points are with the status quo. And then, you must get them to admit to having these pain points. This helps you build trust, and trust is vital - people like to buy from those whom they trust.

Sell by telling stories

Ask your audience a question - get them to tell you their pain points. This is especially a good way to go about the first meeting with a potential client. Once they start talking, now you have to coddle them a little bit. Tell them how you've had other clients with similar problems. Don't say, "I can help you, and here's how -" instead, tell them a story. Say something like, "You know, we had another client who was facing the [...] problem, and we built them a [...] solution that helped them save [...]."

By citing other clients, you're helping the potential client feel better - they're not the only ones with problem X - you're making yourself more relatable to them, and you're still showing off your product/service.

After that, you can follow up with more specific questions.

Keep things open

At least at first. If you have a booth set up in a conference somewhere, or are engaging in that first, initial meeting, don't tell them the nitty-gritty details about your fantastic custom e-commerce solution. At best, they'll talk enthusiastically for a few minutes, and then regretfully tell you that the problem you're solving isn't high-priority for them at the moment.

You must keep things high-level. The problem with getting too far into the details is that the moment the potential client starts focusing on details, the pain points that you had worked so hard to bring up start slipping from their memory. You need to focus on those high-level pains, and present high-level solutions. 

Ask 'how/why' questions, not 'what' questions

This ties in with phrasing - how you say things. Don't ask them what CMS they use, ask they how their experience is with their current CMS. After you've discussed it a little bit, then you can ask lead them to tell you what CMS they are using. The reason for this is that How/Why questions are open-ended;  what questions are close-ended. Especially in the early stages, you always want to keep things open-ended.

WIIFM - What's In It For Me

In the end, it comes down to adding value to the client. There are two means of adding value - time and money. Everything else - no matter what the client sites - can be boiled down to one or both of these two. It helps if you have concrete figures that you can show the client, on what their return on investment would be if they invested in you.

Secondly, it is better to lead the client to the realization that you have the means of saving them time/money. This is a better approach then telling them outright - they will trust their own conclusions better than the conclusions you present.

People buy your passion

Get them excited about you. Share your vision, and how that can help them shape their vision. You want them to buy into your vision.

Silence isn't a bad thing

This is something I have a lot of trouble with - when a potential client is silent, they are thinking. Let the wheels turn - don't feel the need to fill in the seemingly awkward silence. When they feel the need to talk to you, they will.

Ask the right questions

You must lead and direct the discussion, but be careful to do so without appearing to dominate the potential client. You must be in control, and they must feel like they are in control.




Monday, February 10, 2014

Thoughts on the Single Responsibility Principle



Today, while reading 97 things every programmer should know (disclaimer: affiliate link), I came across an explanation of the Single Responsibility Principle that finally clicked for me. I've read a fair amount of literature on Best Practices for programming, but I've often faced trouble in applying these best practices in real life projects. Here was an explanation that finally made sense.


The Single Responsibility Principle says that each class should have only one reason to change. This makes perfect sense in theory, but somehow I just couldn't find a way to implement it in practical code. However, after reading this chapter in the above book, I realized that I was getting the semantics wrong - objects in OOP don't have to correspond to objects in the real world. You don't need to have a single (possibly quite large) class for an Employee that handles the business logic related to Employees (eg. calculating wages, sick days, etc), as well as the database logic (inserting into and retrieving from a database), as well as any report generation logic - classes should be more flexible and correspond to what makes them easier to maintain. 

The chapter linked above, for example, says that instead of having an Employee class with functions that handle business/database/reporting logic, it makes more sense to have an Employee class that handles the business logic, then an EmployeeRepository class for the database logic and an EmployeeReporting class for the reporting logic. This means that if the database logic ever needs to change, I will only be touching the EmployeeRepository class that handles only the database logic. The business and reporting logic will remain untouched in their respective classes. Now, each class truly has only one reason to change.

Conclusion: don't be rigid in insisting on having classes map to real-world entities. Code your classes based on what makes them easiest to read and maintain.