Adrian Mejia's [code]Blog

var life = { "work_hard","have_fun","make_history" };

How Company X Make Money?

| Comments

Have you ever wonder how the companies that offer free services make money? Such as Instagram, Evernote, Facebook, Twitter, LinkedIn, Google Maps, so on… or if it is even profitable to keep free users using their services. We would go through several revenue models and hopefully, it will throw you some light next time you decide to roll your own startup.

TL; DR: Go to the interactive company revenue checker.

Revenues Models

Let’s start first giving some perspective what models are actually giving the most revenues. In 2013, App Store, reported that free apps brought the 71% of the revenue! Even more than paid apps… how’s that even possible!?

(source: techcrunch)

Ok, let’s discuss some revenue models to understand this. There are 3 main models

  • Freemium: apps are free to download and use. However, quite often some different features are sold separately (e.g. new levels, specialized functions, remove ads, more capacity, and so on). E.g. Pandora, Hulu, Google Docs.

  • Premium: users paid upfront a fixed price for the application. After you pay for it, you are able to download it. Usually new software updates are free. E.g. MS Office 365.

  • Subscription: users paid a fixed price which is automatically charged every certain time. Magazines in the iOS Newsstand are a good example of this subscription based model. Subscriptions have generally lower prices than premium accounts. E.g. Netfix.

Freemium is not as “free” as it might seem in the surface, there are indirect ways of getting revenues from it.

  • Advertising: the application/service is free to use, but it contains ads or interruption banners for an couple of minutes in order to raise revenue. This model is usually applied along with freemium apps and to remove the ads users have to pay a subscription. E.g. Spotify.

  • Selling data: user information and behavior inside the application is sell to interested 3rd-parties. Usually used with freemium apps and specified in the terms of used.

  • Transaction: the application is free to use generally and charges a percentage or fixed fee with every users’ transaction made. For example, it allows you to publish your item on their site for free but when you sell it, it charges you a fee. Or publish a project in a site and when it reaches certain goal a percentage fee is applied. E.g. eBay, Kickstarter.

  • Online lead generation: collects user’s information sometimes in an exchange of a product or service and then resell the information to companies interested indirectly. It’s different from the selling data model because the information is not sold to 3rd party directly, but indirectly. Influencing users desitions based on 3rd party companies affiliated and users’ interests, likes and behaviors. E.g. Mint, LinkedIn.

  • Donations: (it’s self-explanatory) Services/apps are free, but it encourages users to contribute throughout donations to support the development.

After reading these, you might have more clues why free apps are so much win nowadays. They helped to create those million-dollar-per-day games! (remembered FlappyBird, Candycrush, Farmville…) In a market where there is enough competition, having a free option will take you to large numbers of users quicker and broader, because of the low barrier to entry. For instance, Whatsapp had at certain point 10k of daily downloads, after moving it to $1 it download rate drops 10 times, they finally opted for yearly subscriptions.

Subscription-based revenue are also a model worth doing a special mention. It brings a steady flow of income to companies and usually comes in different tiers to fulfill users need. But, it has to be flexible enough, because it might limit hard core users which might be willing to pay more for taking the product to a new level.

Click at the companies logos to see if their revenue models are profitable or not. You might get surprised! If some information is not accurate please leave a comment and if you are wondering about another company not listed here, let me know and I will add it :)

    Cheap Airplay Receiver With Raspberry Pi

    | Comments

    I got excited about the idea of having a Raspberry Pi. It is in essence one of the smallest complete computer that you can get for $35 bucks! Ok, after I got one I had to do something useful with it… So I make it a Airplay receiver to play music remotely from any of my apple devices!

    There is a couple of ways to make it work. The easiest one is to install the RaspBMC, a popular media center.(http://www.raspberrypi.org/downloads) You can even turn it into a home theater (http://www.makeuseof.com/tag/raspberry-pi-home-theater-system/). However, I’m not going to explain any of those ways because just installing them gives you 99% of the functionality. As a developer, I want to have control of the computers, and I’m not afraid of the console. So, I installed Raspbian instead, which is a lightweight Ubuntu/Debian Linux optimized for Raspberry Pi.

    Getting started

    1. Install Raspbian “wheezy”

    Download the image from http://www.raspberrypi.org/downloads and follow the instructions. You have to format the SD card and “copy” the image. You can download this formatting tool: https://www.sdcard.org/downloads/formatter_4. After that, plug the SD card in Raspberry, also the Ethernet cable and power cord. For more instructions follow http://lifehacker.com/5976912/a-beginners-guide-to-diying-with-the-raspberry-pi.

    2. Setup Pi

    You need to connect it to an HDMI display to set it up using a USB mouse and keyboard or you can use SSH if you had set that up.

    3. Access the Terminal

    From the terminal type the following commands in you Raspberry Pi:

    Become root and update the system

    1
    
    sudo apt-get update && sudo apt-get upgrade
    

    3. Setup Audio

    Audio ports could either be bind to the HDMI connection or to the audio output jack (you need sudo to execute any sound command).

    1
    
    sudo amixer cset numid=3 1
    

    Connect the speakers to you Raspberry Pi. You can test that they work with these:

    1
    2
    
    sudo speaker-test -t pink -l 1
    sudo speaker-test -t sine -l 1
    

    You can also adjust the volume

    1
    
    sudo alsamixer
    

    4. Install Airplay software

    I tested with 2 different programs, both of them did the trick for me.

    The latter is more popular so I will give the instructions for that one:

    1
    2
    3
    4
    5
    6
    
    apt-get install -y libssl-dev libavahi-client-dev libasound2-dev git
    git clone https://github.com/abrasive/shairport.git
    cd shairport
    ./configure
    make
    ./shairport -a 'AirPi'
    

    5. Run Airplay (shairport) on boot.

    It’s nice to run airport receiver automatically when you connect your Pi.

    Create a file to start shairport

    1
    
    nano /etc/init.d/airplay
    

    Type the following into airplay:

    airplay
    1
    2
    
    #!/bin/bash
    /usr/local/bin/shairport -a "AirPi"
    

    Close the editing mode and exit the file. Then register the script to be run on boot.

    1
    2
    
    chmod a+x /etc/init.d/airplay
    update-rc.d airplay defaults
    

    Reboot your Pi and you are good to go! (If you have any questions you can write a comment below)

    Algorithms for Dummies (Part 1): Big-O Notation and Sorting

    | Comments

    After being developing software for a while, I realized that there is a couple of ways to become better at it. One it’s through your experience: writing code, working on projects, getting hands dirty… Other one it’s learning algorithms and design patterns. In other words through leveraging the experience of other computer scientists. Learning to use algorithms efficiently can instantly add to you the equivalent of 10 years of experience or more. Let’s get started and add new tools to our arsenal!

    How do you know a piece of code that you just wrote is good enough? When you modify a program, how do you know if it is better as you found it? How do scale programs to handle huge amount of data? In fact, You cannot improve what you can’t measure.

    How to measure them? We could count the number of seconds it takes to execute and compare it with other one. However, it’s not just troublesome to timers around code but if we run it in different hardware (e.g. supercomputer) it will seem like more efficient when indeed it’s exactly the same program. Let’s illustrate a better way with an example. Let’s say you want to sort an array of n integers.

    Sorting Algorithms

    1
    2
    3
    4
    5
    6
    7
    8
    
      void sort(int[] arr){
        for(int x=1; x < arr.length; x++)
          for(int y=x; y > 0 && arr[y-1] > arr[y]; y--){
              int t = arr[y];
              arr[y] = arr[y-1];
              arr[y-1] = t;
            }
      }
    

    Do you recognize this algorithm? It’s called Insertion sort. It has two nested loops, which means that as the number of elements n in the array arr grows it will take approximately n * n longer to perform the sorting. In big-O notation, this will be represented like O(n2). More on this notation later.

    What would happen if the array arr is already sorted? That would be the best-case scenario. The inner for loop will never go through all the elements in the array then (because arr[y-1] > arr[y] won’t be met). So the algorithm in run in O(n).

    We are not living in an ideal world. So O(n2) will be probably the average time complexity. Can you think a better way of sorting an array of elements?

    Take some minutes to think and come back…

    Merge Sort

    A more efficient algorithm is the Merge sort. It uses the principle of divide and conquer to solve the problem faster. The idea is the follows:

    • Divide the array in half
    • Divide the halves by half until 2 or 3 elements are remaining
    • Sort each of these halves
    • Merge them back together

    Can you determine the time complexity of mergesort?

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    
      void sort(int[] arr){
        int[] helper = new int[arr.length];
        mergesort(arr, helper, 0, arr.length-1);
      }
    
      void mergesort(int[] arr, int[] helper, int low, int high){
        if(low < high){
          int middle = (high+low)/2;
          mergesort(arr, helper, low, middle);
          mergesort(arr, helper, middle+1, high);
          merge(arr, helper, low, middle, high);
        }
      }
    
      void merge(int[] arr, int[] helper, int low, int middle, int high){
        for (int x=low; x <= high; x++) {
          helper[x] = arr[x];
        }
    
        int left = low;
        int curr = low;
        int right = middle+1;
    
        while(left <= middle && right <= high) {
          if(helper[right] > helper[left])
            arr[curr++] = helper[left++];
          else
            arr[curr++] = helper[right++];
        }
    
        while(left <= middle)
          arr[curr++] = helper[left++];
      }
    

    Even though the code is much longer, the algorithm is much more efficient.

    It would take some more knowledge to derive the running time mathematically, and we haven’t covered that yet. However, bear with me, it’s O(n log(n)). Let’s sum up:

    Algorithm best average worst space complexity
    Insertion Sort O(n) O(n2) O(n2) O(1)
    Merge sort O(n log(n)) O(n log(n)) O(n log(n)) O(n)

    Notice that the table has also the space complexity. How much space does the algorithms take is also an important parameter to compare algorithms. The merge sort uses an additional array that’s way its space complexity is O(n), however, the insertion sort uses O(1) because it does the sorting in-place.

    Big O Notation

    Big O is defined as the asymptotic upper limit of a function. In plain english, it means that is a function that cover the maximum values a function could take. As we saw a little earlier this notation help us to predict performance and compare algorithms.

    Growth RateName
    1Constant
    log(n)Logarithmic
    nLinear
    n*log(n)Linearithmic
    n^2Quadratic
    n^3Cubic
    2^nExponential

    This is kinda abstract let’s see what it means in code:

    Growth RateNameCode e.g.description
    1Constanta+=1;statement (one line of code)
    log(n)Logarithmic
    while(n>1){
      n=n/2;
    }
    
    Divide in half (binary search)
    nLinear
    for(c=0; c<n; c++){
      a+=1;
    }
    
    Loop
    n*log(n)LinearithmicMergesort, Quicksort, …Effective sorting algorithms
    n^2Quadratic
    for(c=0; c<n; c++){
      for(i=0; i<n; i++){
        a+=1;
      }
    }
    
    Double loop
    n^3Cubic
    for(c=0; c<n; c++){
      for(i=0; i<n; i++){
        for(x=0; x<n; x++){
          a+=1;
        }
      }
    }
    
    Triple loop
    2^nExponentialTrying to braeak a password generating all possible combinationsExhaustive search

    That’s all for this first part 1. I will continue publishing this tutorials every week or so. Stay tune!

    Backbone.js for Absolute Beginners - Getting Started (Part 4: Routers)

    | Comments

    The part 3 of this tutorial is here.

    2.6 Backbone.Router

    You could build web application without using the routers. However, if you want to make reference to certain ‘state’ or location of the web application, you need a reference (link/URL) to it. This is where routers come to rescue.

    Routing in most of JS application are achieved by hash-tags. E.g. If you take a look of Gmail URL you will see something like:

    https://mail.google.com/mail/u/0/#inbox/139c0d48e11d986b

    where the #inbox/139c0d48e11d986b is the hash-tag which reference some email location.

    In backbone, routes are hash maps that match URL patterns to functions. You can use parameter parts, such as todos/:id, or using splats file/*path you will match all the parameters from the splat on. For that reason, the splat parameter should be always the last matcher.

    2.6.1 Initializing the Router

    In our Todo app, we are going to use routers to filter between the tasks that are pending and the ones that have been completed. So, let’s initialize the routes this way:

    Define RouterFull Code
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
        app.Router = Backbone.Router.extend({
          routes: {
            '*filter' : 'setFilter'
          },
          setFilter: function(params) {
            console.log('app.router.params = ' + params); // just for didactical purposes.
            window.filter = params.trim() || '';
            app.todoList.trigger('reset');
          }
        });
    

    Now, you need to initialize it, adding this lines:

    Initialize routerFull Code
    1
    2
    3
    4
    5
    6
    7
    
         //--------------
         // Initializers
         //--------------
    
    +    app.router = new app.Router();
    +    Backbone.history.start();    
         app.appView = new app.AppView();
    

    You can test that you router is working just typing #anything/that/you/want and seeing the parameter in you browser’s console.

    2.6.1 Processing the routes

    Before rendering the list of items, you need to check the parameters to wether show only the pending ones, or the completed or show them all. As shown in the code snipet below.

    Processing the routes in app.AppViewFull Code
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    
    @@ -164,7 +177,18 @@
           },
           addAll: function(){
             this.$('#todo-list').html(''); // clean the todo list
    -        app.todoList.each(this.addOne, this);
    +        // filter todo item list
    +        switch(window.filter){
    +          case 'pending':
    +            _.each(app.todoList.remaining(), this.addOne);
    +            break;
    +          case 'completed':
    +            _.each(app.todoList.completed(), this.addOne);
    +            break;            
    +          default:
    +            app.todoList.each(this.addOne, this);
    +            break;
    +        }
           },
           newAttributes: function(){
             return {
    

    If you try adding the words #/pending or #/completed at the end of the URL you’ll get an error!. That’s a good sign, it means the routes are working, but we haven’t implemented the app.todoList.remaining() and app.todoList.completed(). So, that’s next:

    Defining ‘completed’ and ‘remaining’ functions in app.TodoListFull Code
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    
    @@ -85,7 +90,15 @@
         //--------------
         app.TodoList = Backbone.Collection.extend({
           model: app.Todo,
    -      localStorage: new Store("backbone-todo")
    +      localStorage: new Store("backbone-todo"),
    +      completed: function() {
    +        return this.filter(function( todo ) {
    +          return todo.get('completed');
    +        });
    +      },
    +      remaining: function() {
    +        return this.without.apply( this, this.completed() );
    +      }      
         });
    

    Now, if you try again adding the hash-tags it will work! But, it will be better if the user can have links to that instead of typing URLs. So, let’s add them.

    Show routes’ linksFull Code
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
    @@ -32,6 +32,11 @@
         <header id="header">
           <h1>Todos</h1>
           <input id="new-todo" placeholder="What needs to be done?" autofocus>
    +      <div>
    +        <a href="#/">show all</a> |
    +        <a href="#/pending">show pending</a> |
    +        <a href="#/completed">show completed</a>
    +      </div>      
         </header>
         <section id="main">
           <ul id="todo-list"></ul>
    

    Well, that’s all! If completed these 4 parts tutorial you will be familiar with the main Backbone modules (Models, Collections, Views, Events, and Routes). To increase you knowledge you can follow the following resources:

    Hope it was helpful!

    Backbone.js for Absolute Beginners - Getting Started (Part 3: CRUD)

    | Comments

    The part 2 of this tutorial is here.

    2.5 Todo item list CRUD

    There are a couple of features that we could improve. Let’s implement the CRUD (Create-Read-Update-Delete) for the item list.

    2.5.1. C-reate

    We are already can create item list from the console (2.3) and also from the UI (2.4.3). So, it’s done.

    2.5.2. U-pdate

    What if you make a mistake and want to change the text on some of your to-do list. Furthermore, you can notice that the checkboxes states are not persistent when you reload the pages. Let’s fix both problems.

    1.– You want to respond to a double click event showing up a text box, where the user can change the text. First, let’s add the HTML in the item-template template below the label tag.

    <input class="edit" value="<%- title %>">

    2.– If you refresh, you will notice that there are both displaying at the same time. So, you can hide them properly with the following CSS.

    CSSFull Code
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
        #todo-list input.edit {
          display: none; /* Hides input box*/
        }
        #todo-list .editing label {
          display: none; /* Hides label text when .editing*/
        }
        #todo-list .editing input.edit {
          display: inline; /* Shows input text box when .editing*/
        }
    
    

    3.– Then, we need to add the events to the TodoView class to respond to the changes.

    Todo ModelFull Code
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    
        // renders individual todo items list (li)
        app.TodoView = Backbone.View.extend({
          tagName: 'li',
          template: _.template($('#item-template').html()),
          render: function(){
            this.$el.html(this.template(this.model.toJSON()));
            this.input = this.$('.edit');
            return this; // enable chained calls
          },
          initialize: function(){
            this.model.on('change', this.render, this);
          },
          events: {
            'dblclick label' : 'edit',
            'keypress .edit' : 'updateOnEnter',
            'blur .edit' : 'close'
          },
          edit: function(){
            this.$el.addClass('editing');
            this.input.focus();
          },
          close: function(){
            var value = this.input.val().trim();
            if(value) {
              this.model.save({title: value});
            }
            this.$el.removeClass('editing');
          },
          updateOnEnter: function(e){
            if(e.which == 13){
              this.close();
            }
           }
        });
    

    You can find the diff that were added to implement the update feature.

    Here are the changes to fix the update for the checkboxes.

    2.5.2. D-elete

    To be able to remove to-do items, we need to add a remove button in each item and listen to the click event on it, which will trigger the destroy function in the selected todo object.

    1.– Add the HTML markup for the remove button.

    Remove Button into ‘item template’Full Code
    1
    2
    3
    4
    5
    6
    7
    
    @@ -47,6 +47,7 @@
           <input class="toggle" type="checkbox" <%= completed ? 'checked' : '' %>>
           <label><%- title %></label>
           <input class="edit" value="<%- title %>">
    +      <button class="destroy">remove</button>
         </div>
       </script>
    

    2.– Listen for the click event in the button that you just created.

    Add event listeners for the Remove Button in ‘app.TodoView’Full Code
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    
    @@ -105,12 +106,14 @@
           },
           initialize: function(){
             this.model.on('change', this.render, this);
    +        this.model.on('destroy', this.remove, this); // remove: Convenience Backbone'
           },
           events: {
             'dblclick label' : 'edit',
             'keypress .edit' : 'updateOnEnter',
             'blur .edit' : 'close',
    -        'click .toggle': 'toggleCompleted'
    +        'click .toggle': 'toggleCompleted',
    +        'click .destroy': 'destroy'
           },
           edit: function(){
             this.$el.addClass('editing');
    

    3.– Add the destroy method to the TodoView.

    Add the destroy method to ‘app.TodoView’Full Code
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
    @@ -130,7 +133,10 @@
           },
           toggleCompleted: function(){
             this.model.toggle();
    -      }
    +      },
    +      destroy: function(){
    +        this.model.destroy();
    +      }      
         });
    

    You can download the full working code so far in here and you can visualize the changes needed to implement the delete feature in here

    Continue with the 4th part and learn about Backbone’s Routes!