Author: avin

  • Financial Comparison of Air Conditioners

    I’ve been looking to get ducted AC installed at my residence and have had a few quotes come in. As the AC units, zoning and controls came with a similar set of features, I investigate the decision from an objective financial standpoint by ranking the offerings by comparing both the capital and operating costs. The rank* is calculated by:

    ac_equation

    where
    capital_cost is the total installation price in dollars
    number_of_years is the number of years the AC will be in operation
    cost_per_unit_capacity is the electricity price (e.g. cents per kWh)
    max_cooling_usage is the number of hours per year the AC will run on max cooling capacity
    min_cooling_usage is the number of hours per year the AC will run on min cooling capacity
    max_heating_usage is the number of hours per year the AC will run on max heating capacity
    min_heating_usage is the number of hours per year the AC will run on min heating capacity
    cooling_input_power is the rated input power in kW for cooling
    heating_input_power is the rated input power in kW for heating
    min_cooling_capacity is the minimum cooling capacity in kW
    min_cooling_capacity is the minimum heating capacity in kW
    min_eer is the min EER (Energy Efficiency Ratio) out of all the ACs being compared
    current_eer is the EER of this particular AC
    min_cop is the min COP (Coefficient Of Performance) out of all the ACs being compared
    current_cop is the COP of this particular AC

    I use the term rank rather than Total Cost of Ownership since I don’t bother discounting future cashflows nor take into account maintenance (since I couldn’t get a hold of spare parts price lists).

    Most spec sheets also don’t provide an input power at min capacity, so the calculation tries to make an estimate based on the EER/COP, input power and min capacity. For those that do provide an input power at min capacity, the 2nd and 4th components within the parentheses can be made similar to the 1st and 4th components.

    Ironically, I ended up choosing the AC ranked second, because of a qualitative aspect – the brand value that would have a bearing on price and availability of spare parts required outside the warranty period.

  • Selecting by Option Value using Capybara

    Capybara’s select command allows searching a HTML select field and selecting an option that matches the supplied value by name, id or label text. Additionally, the match option allows the user to indicate the behaviour if more than one option is found. For example, match: :first will select the first item out of multiple matches, while match: :one will throw an error if more than one item is found.

    I was recently dealing with a time zone select list based on ActiveRecord::TimeZone. I was receiving an error when Capybara tried to select “Samoa” from the option list (“Samoa” due to test randomisation), since there were items named “American Samoa” and “Samoa”. I ended up having to select the option via its ‘value’ attribute instead:

    time_zone = ActiveRecord::TimeZone.all.sample
    find('select#time_zone').find("option[value='#{time_zone.name}']").select_option
  • Auto-Mounting VirtualBox Shared Folders with a Linux Guest OS

    VirtualBox has a feature where a folder on the host machine can be shared with a guest VM. VirtualBox can also mount these shared folders automatically when the user logs into the guest OS. For Linux guests, these auto-mounted shared folders are mounted into the /media directory, along with the prefix sf_. For example, the shared folder sharedfiles will be mounted to /media/sf_sharedfiles.

    As only the user group vboxsf is granted permissions to the auto-mounted shared folders, you’ll need to add your user to the group to access the shared folder. Otherwise you’ll get a “Permission denied” error when trying to navigate to the shared folder.

    sudo gpasswd -a username vboxsf
    

    Make sure you log out of the guest OS, then log in again for the group membership to take effect.

  • History of Christianity

    Continuing the theme of history-based studies, the latest youth group study I led was on the History of Christianity. There is an incredible amount of literature available online, and we only covered a small fraction of events from Early Christianity and investigating the major groups of denominations. We also had a look at how Christianity and the churches in India formed particularly with their interaction with the western churches, and this was personally fascinating. Another group member covered the Crusades, while the Reformation will be covered in our next study. Here are the slides I used and make sure you have a look at the notes section for the talking points. I did use a special font for the title slide if it looks strange.

  • Intro to Data Modelling

    When I was working for the Information and Data Management practice at SMS Management & Technology a few years back, I was asked to run a workshop for the Business Analysis Focus Group on data modelling. I put together an introductory presentation on data modelling targeted towards business analysts, which was a refresher on terminology and approaches. At the end of the presentation, I paired up everyone in the audience for two data modelling exercises: one person would act as a client while the other would act as a data analyst, eliciting data requirements and identifying a conceptual/logical data model. There were two scenarios so each person had an opportunity at the data analyst role, and both scenarios were based on real world projects I had previously worked on.

    Download presentation
    Download scenarios

  • Using Rails’ descendants in development

    Rails provides a nice method descendants that returns all subclasses for a specified class. However, config.cache_classes = false is a default setting in development.rb (for the ability to reload classes on the fly) and as this tells Rails not to load classes until they are referenced, then calling descendants will generally return an empty array not the expected subclasses.

    To be able to use descendants in development, you can add the following code to development.rb:

    config.eager_load_paths += Dir['path/to/files/*.rb']
    ActionDispatch::Reloader.to_prepare do
    Dir['path/to/files/*.rb'].each {|file| require_dependency file}
    end
    

    The first line tells Rails to load these particular files when Rails first starts up. The rest of the code tells Rails to require these particular files (including any new files/classes) on each request.

    Note: if your path/to/files isn’t one of the standard directories that Rails watches (to trigger the reloader), you will need to add it to config.watchable_dirs:

    config.watchable_dirs['path/to/files/'] = [:rb]
    

  • Islam

    I decided to do a series of studies for our church youth group on various religions and started with Islam as Muslims form the second largest religious group globally. The intent was to cover the fundamentals of the Islamic faith, common terms that people may have come across, a brief history, and Islam’s relation to India, Christianity, and our local city. I’ve uploaded the notes I used.

  • Malayalam TV

    Like most of the older folk in my ethnic community, my grandparents enjoy watching Malayalam television programming. They had jumped on the satellite bandwagon a few years ago and got good mileage out of it. However, at the end of 2011, Asianet, one of the primary channels they watch, moved from Insat 2E to Intelsat 17. The shift to the more westerly satellite had the unfortunate consequence of removing coverage from the eastern seaboard of Australia.

    A lot of disappointed Malayalees in Sydney, Melbourne and Brisbane had to find alternatives for getting their Malayalam TV fix. My grandparents found their saviour in BomTV, which provided live steaming via the Internet albeit on a subscription basis. This required a Roku (or Android) device, which was provided with the initial subscription to a package. The streaming quality wasn’t as good as satellite and the device would need to occasionally buffer, but it was adequate.

    Recently, my grandparents needed to replace their TV and they ended up purchasing a smart TV with Internet browsing. Also, through my grandmother’s exploratory searching, they found that they could view Malayalam (along with other Indian language) TV content online using Bharat Channels. While it wasn’t real-time TV, they could select what they wanted to watch, whenever they wanted to watch, and it was free and without ads. Poking around, I noticed the website simply pointed to YouTube for all their content. I’m unsure if it is indeed the Indian TV channels themselves posting the content (as opposed to a third-party) but either way, it’s probably a good monetisation strategy for somebody.

    The Bharat Channels website is obviously designed for a desktop (and not a TV) and adds a lot of visual noise. In order to streamline their viewing experience, I created a simple website that serves up the same YouTube content, but packaged in a more user-friendly way: Malayalam TV.

    Using PHP and Twitter Bootstrap (for a responsive design), the script reads a specified YouTube channel’s RSS feed and displays the content as easy to click thumbnails. The thumbnails link to a full screen version of the video. Surprisingly, an iPad’s Safari browser requires a different link: http://www.youtube.com/embed/{id} vs. http://www.youtube.com/v/{id} while an iPhone doesn’t. I also had to use CSS media queries to lock the dimensions of the thumbnails, since certain videos have quite long titles. I did look into CSS’s text-overflow: ellipsis options, but this doesn’t work across multiple lines. While there are several JavaScript truncation libraries, in trying to be as minimal as possible, I just went for the quick and crude approach. This theme also carried over into the CSS, where only used CSS from Twitter Bootstrap was included.

    See the code on GitHub.

  • Coloured directory listings in PowerShell

    By default, PowerShell outputs drab directory listings. Unfortunately, there’s no built in solution to turning on colour, but it is possible with a few steps.

    1. This StackOverflow post gets us most of the way there. Towards the bottom of the question is some code that enables colourised output. I’ve modified it to suit my purposes (see below). This code should be put in your profile (see $profile to find the location).
    2. As noted, the code depends on the New-CommandWrapper cmdlet from the Powershell Cookbook. In my PowerShell profile directory, I’ve created a Scripts directory as a sibling to the regular Modules directory and put the cmdlet there.
    3. Ensure New-CommandWrapper.ps1 is unblocked (right click, Properties, Unblock) and in your PATH. If using the Scripts directory, you can put $env:Path += ";$(Split-Path $profile)\Scripts" in your profile.
    4. Using Set-ExecutionPolicy, ensure your execution policy is set to RemoteSigned or Unrestricted.
    5. Start a new shell, type dir or ls and enjoy.

    As mentioned, I’ve modified the code in the StackOverflow post to suit my needs:

    • Cyan instead of Magenta directories. Magenta hurt my eyes.
    • Ignoring colouring text files separately as yellow. I have a lot of text files using different extensions and colouring text files didn’t provide any benefit.
    • Removed Perl, Python and Ruby extensions from executables. I don’t use Perl or Python and I have more Ruby code as part of a Rails app than standalone scripts.
    • Adjusted column spacing.
    • Don’t output a length for directories. It doesn’t show in the screenshot, but it displayed a length of 1 for directories.
    • Add coloured file count along with total file size at bottom.
    • Override both dir and ls aliases.
    • Renamed functions according to PowerShell verb-noun conventions.

    The code that goes in your profile is:

    New-CommandWrapper Out-Default -Process {
      $regex_opts = ([System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
      $compressed = New-Object System.Text.RegularExpressions.Regex(
        '\.(zip|tar|gz|rar|jar|war)$', $regex_opts)
      $executable = New-Object System.Text.RegularExpressions.Regex(
        '\.(exe|bat|cmd|msi|ps1|psm1|vbs|reg)$', $regex_opts)
    
      if(($_ -is [System.IO.DirectoryInfo]) -or ($_ -is [System.IO.FileInfo]))
      {
        if(-not ($notfirst))
        {
          Write-Host "`n    Directory: " -noNewLine
          Write-Host "$(pwd)`n" -foregroundcolor "Cyan"
          Write-Host "Mode        Last Write Time       Length   Name"
          Write-Host "----        ---------------       ------   ----"
          $notfirst=$true
        }
    
        if ($_ -is [System.IO.DirectoryInfo])
        {
          Write-Host ("{0}   {1}                {2}" -f $_.mode, ([String]::Format("{0,10} {1,8}", $_.LastWriteTime.ToString("d"), $_.LastWriteTime.ToString("t"))), $_.name) -ForegroundColor "Cyan"
        }
        else
        {
          if ($compressed.IsMatch($_.Name))
          {
            $color = "DarkGreen"
          }
          elseif ($executable.IsMatch($_.Name))
          {
            $color =  "Red"
          }
          else
          {
            $color = "White"
          }
          Write-Host ("{0}   {1}   {2,10}   {3}" -f $_.mode, ([String]::Format("{0,10} {1,8}", $_.LastWriteTime.ToString("d"), $_.LastWriteTime.ToString("t"))), $_.length, $_.name) -ForegroundColor $color
        }
    
        $_ = $null
      }
    } -end {
      Write-Host
    }
    
    function Get-DirSize
    {
      param ($dir)
      $bytes = 0
      $count = 0
    
      Get-Childitem $dir | Foreach-Object {
        if ($_ -is [System.IO.FileInfo])
        {
          $bytes += $_.Length
          $count++
        }
      }
    
      Write-Host "`n    " -NoNewline
    
      if ($bytes -ge 1KB -and $bytes -lt 1MB)
      {
        Write-Host ("" + [Math]::Round(($bytes / 1KB), 2) + " KB") -ForegroundColor "White" -NoNewLine
      }
      elseif ($bytes -ge 1MB -and $bytes -lt 1GB)
      {
        Write-Host ("" + [Math]::Round(($bytes / 1MB), 2) + " MB") -ForegroundColor "White" -NoNewLine
      }
      elseif ($bytes -ge 1GB)
      {
        Write-Host ("" + [Math]::Round(($bytes / 1GB), 2) + " GB") -ForegroundColor "White" -NoNewLine
      }
      else
      {
        Write-Host ("" + $bytes + " bytes") -ForegroundColor "White" -NoNewLine
      }
      Write-Host " in " -NoNewline
      Write-Host $count -ForegroundColor "White" -NoNewline
      Write-Host " files"
    
    }
    
    function Get-DirWithSize
    {
      param ($dir)
      Get-Childitem $dir
      Get-DirSize $dir
    }
    
    Remove-Item alias:dir
    Remove-Item alias:ls
    Set-Alias dir Get-DirWithSize
    Set-Alias ls Get-DirWithSize
    

  • Moving to a Windows JRuby on Rails development environment

    tl;dr I recently set up a JRuby on Rails development environment on Windows after using Mac OS X and Ubuntu VMs. It’s noticeably faster for development and more comfortable. I’ll stick with it.

    When I was first starting JRuby on Rails development, I started with a Mac OS X environment running from VirtualBox. I chose Mac OS X to emulate as close as possible what the other members in my team were using, so I could get advice on the basics without too much friction. However, Mac OS X isn’t officially supported by VirtualBox and the environment was unwieldy – no ability to resize the VM window, no shared clipboard and occasionally crashes on boot were the main drawbacks.

    After a few weeks, I moved to an Ubuntu VM. This did require minor adjustment in our codebase to get it working on a development environment. VirtualBox supports Ubuntu, and the drawbacks from the Mac OS X experience were eliminated. I used this environment for a good eight months, and became quite familiar with Unix environment. The terminal took the forefront (compared to Windows), apt-get package management was fantastic and everything felt solid. However, after copying the VM to my laptop, running Rails and tests was considerably slow.

    Another reason I initially avoided Windows as a development environment was the common perception at the time was that Windows was a second-class citizen in the Ruby community, and performance was lacking. Supposedly even a Ubuntu VM would outperform a native Windows environment. Having gained significant experience with JRuby on Rails over the last few months, I felt comfortable enough to try my hand at setting up a Windows development environment. Here’s what I learnt from the process:

    • Use the Java SDK instead of Java JRE to run JRuby. I would occasionally get Cannot find Java 1.5 or higher error messages when running certain gems. Ensure JAVA_HOME is set to Program Files/Java/jdk* and PATH includes Program Files/Java/jdk*/bin.
    • JRuby on Windows requires the jruby-pageant gem to interact with net/ssh.
    • We are using Eco templates and I was encountering Encoding::Compatibility Error, incompatible character encodings: UTF-8 and Windows-1252 errors when trying to compile a Javascript template that had a UTF-8 character. UTF-8 characters in ERB templates displayed correctly. I couldn’t solve this one and ended up using the escaped HTML format instead.
    • Command Prompt and Powershell don’t natively support ANSI escape characters (e.g. colour codes). So running RSpec would insert a bunch of garbage characters in the output. Turning off --color helped, but there was still some around the progress bar itself, notwithstanding the loss of coloured output. I investigated ANSICON but it seemed too complex to install and I wasn’t entirely sure I could get it working with Powershell. So I decided to install Cygwin and while doing so, thought I’d use ConEmu to unify my Cygwin and Powershell terminals under one umbrella. That’s when I found Powershell, when run through ConEmu, supports colour codes and also allowed me to navigate through irb/rails console history.
    • I found PuTTY itself more convenient than running plink through Powershell as it seems to better interact with bash. PuTTY can also be set up as a task/jump-list in ConEmu to avoid typing the full command.
    • You have to add your private RSA key to Pageant. I always wondered what the computer icon with the hat in my taskbar was for.
    • Use PowerTab with PowerShell. It uses bash-like tab completion instead of the default cycling completion.

    In the end, it’s about performance and friction. In comparison with the Ubuntu VM environment, JRuby start up time is noticeably quicker although running the entire test suite is mixed – its faster when using Poltergeist/PhantomJS for integration/feature tests, while slower using Selenium (which we’ve since abandoned). This leads me to think the original performance advice of using a Unix system was based on experience with MRI rather than JRuby.

    The Windows environment itself is more familiar and I can now Alt-Tab between my IDE, terminals, file manager, and browser, and move applications to different monitors. As there are no showstoppers, I’ll be sticking with this environment for the foreseeable future.