• Setting up remote debugging for Google Chrome on Android

    I’ve recently needed to debug a web application on Android and if you haven’t noticed - there are no Developer Tools for the mobile Google Chrome. Pity.

    However there is a handy feature built in into Google Chrome on Android called “USB Web Debugging”, which allows you to connect your Android device to a computer and debug it there. Handy! Now here’s how to set it up:

    Setting it up

    It is supposed to only work with Chrome Beta, Chrome Dev and Chrome Canary channel versions, but for me it did work on Chrome Stable. If these steps don’t work for you, you may need to go via the Android SDK route, so for that please check the official guide: Remote Debugging with Chrome and ADBPlugin. Alright, let’s get going.

    On your Android device

    There are two things you will need to enable on your Android device:

    1. USB Debugging - Settings > Developer options > Check “USB debugging”. If you’re using an older version of Android (I’ve written this guide for Android 4.1), this option may be found in other place or even hidden.
    2. USB Web debugging - Chrome > Settings > Developer tools > Check “Enable USB Web debugging”.

    Once you’ve done that - the device is ready for action! Just don’t forget to connect the device via USB to your computer. Now we only need to do a couple of things on your computer…

    On your computer

    1. Install the official ADBPlugin Chrome Extension from the Play Store
    2. Click on the Android icon in your Chrome menu and select “Start ADB”.
    3. Click on the Android icon in your Chrome menu and select “View inspection targets” or go straight to chrome://inspect. You should see the device and open windows listed there. The first time I did this it didn’t work for me, but a restart of Chrome on both devices and reconnecting the USB cable helped.
    4. Click inspect next to the desired entry to open up Chrome Developer Tools to start inspecting the page!

    And that’s pretty much it! It’s that simple to get going. And props for people who created this as it makes mobile development so much easier and more convenient. Personally, I’ve been blown away by it.

    If you have any questions, notes or suggestions, please let me know below in the comments section and I will do my best to answer them.

  • The Factory Pattern: Design Patterns

    It’s been a while since we’ve looked at designed patterns, so let’s continue our journey of design pattern adventures by looking at the Factory pattern.

    What is it and why use it?

    One of the larger problems in software development is tight coupling of system components. It is a problem, because:

    • it makes it harder to test components - we have to worry about constructing large pieces of the component, managing dependencies, creating test cases
    • it makes it difficult to swap certain components for others - for instance, say we’ve been using SQLLite database when the system was small. Now it got much larger than you anticipated and you need to migrate to another database (say Oracle, PostgreSQL, MySQL or any other). If we’ve done a bad job and coupled everything tightly - we would need do to a lot of work and change many things. On the other hand, if we’re lucky - it may need changes only in a few places.

    Factory design pattern is a creational design pattern, that takes over and abstracts creation of objects. Basically, instead of creating objects with a new keyword, one asks the factory to create that object and that’s pretty much it.

    It may seem that it only adds unnecessary overhead, however it does have advantages:

    • often certain information or resources, which should not exist within a user class, are required in order to create an object. Factory pattern helps to hide and manage dependencies and without tasking the user class to handle it
    • it helps to reduce code duplication - complex object initialization can be kept in one place (Keep it DRY - Don’t Repeat Yourself)
    • makes testing easier - factory methods can be overridden to return objects that are needed for testing

    Code examples

    It may be difficult to understand how it works, so let’s come up with an example.

    Let’s say we have a game board that can have many players on it. Each player has it’s own name and coordinates (x, y). After creating players we want to run the game and see where players are.

     * Let's say we have a game board that can have many players on it. Each player
     * has it's own name and coordinates (x, y).
     * After creating players we want to run the game and see where players are.
    class Player {
        public function __construct($name, $x, $y) {
            $this->name = $name;
            $this->x = $x;
            $this->y = $y;
        public function getName() {
            return $this->name;
        public function getPosX() {
            return $this->x;
        public function getPosY() {
            return $this->y;
    class GameBoard {
        public function __construct() {
            $this->players = array();
        public function registerPlayer(Player $player) {
            $this->players[] = $player;
        public function run() {
            foreach ($this->players as $player) {
                        "%s is on (%d, %d)\n",
    class GameFactory {
        private static $gameBoard;
        public static function createBoard() {
            if (!GameFactory::$gameBoard) {
                GameFactory::$gameBoard = new GameBoard();
            return GameFactory::$gameBoard;
        public static function createPlayer($name, $x, $y) {
            $player = new Player($name, $x, $y);
            return $player;
    // Create and run our game
    $board = GameFactory::createBoard();
    $jim = GameFactory::createPlayer("Jim", 1, 0);
    $bob = GameFactory::createPlayer("Bob", 10, 7);

    So as you can see we are hiding how players are registered to the board. Client classes don’t need to know about the game board anymore - they only need to pass the data to the GameFactory and the object will be created. But now we can easily add different types of players (e.g. guests, administrators, registered users) if needed.

    Though it may not be a good idea to always register players to a board as they may need to be not on it, but for the sake of the example that’s our “difficult object initialization”.

    Last thoughts

    Factory design pattern is one of the most used design patterns and it helps to solve certain software design problems, however as Fred Brooks said “There is no silver bullet”. If used incorrectly, Factory Design pattern may cause problems (e.g. increase in coupling between classes or components).

    The code I used for this post and other posts about design patterns (Singleton, Observer) can be found in my repository on Github flakas/Design-patterns.

    For further reading I suggest you these links:

  • Compute hamming distance of byte arrays in Scala

    Hamming distance is the number of positions in which two different strings are different.

    So the distance between both strings would be:

    • “abcde” and “abede” - 1
    • momomo” and “nonono” - 3

    Implementing this would not be difficult:

    def hammingDistance(s1: String, s2: String): Int = s1.zip(s2).count(c => c._1 != c._2)

    Basically you zip ("abc".zip("bcd") produces scala.collection.immutable.IndexedSeq[(Char, Char)] = Vector((a,b), (b,d), (c,e))) strings together and compare corresponding characters. Simple, right?

    However, the task I was working on required comparing individual bits, which are slightly more tricky to get to. I couldn’t find quickly any public snippets that do this, so I wrote my own:

    To get the number of different bits of two bytes we only need to XOR them and compute how many bits are set:

    For example: 0b10010101 XOR 0b01011101 = 0b11001000.

    To calculate the number of bits set we just shift the XORed byte i number of times and AND 1 to get rid of other bits.

    This method has a performance flaw as it shifts i times for each bit as opposed to shifting once per bit and relying on previous results, but oh well - it’s suitable when high performance is not necessary.

  • "Functional Programming Principles in Scala" online Coursera course

    This spring I have taken a “Functional Programming Principles in Scala” online course, taught by professor Martin Odersky from École Polytechnique Fédérale de Lausanne (Course website).

    It is intented to teach about functional programming and Scala totally from scratch, however some programming experience is required (Java/C# is recommended, C/C++/Python/Javascript/Ruby is sufficient). The course duration is 7 weeks with 5-10 hours of workload each week, however I averaged at about 4 hours.

    Course Syllabus

    • Week 1: Functions and Evaluations - overview of functional programming, scala
    • Week 2: Higher Order Functions - recursion, currying, using functions as values
    • Week 3: Data and Abstraction - classes, immutable objects, polymorphism
    • Week 4: Types and Pattern Matching - pattern matching, types, subtypes and generics
    • Week 5: Lists - working with lists, list reduction
    • Week 6: Collections - maps, for translations, search
    • Week 7: Lazy Evaluation - streams, lazy evaluation, infinite sequences


    In total there were 6 assignments with 1 week for catching up. Each week a new assignment would be published along with handout archive file and a description of problems.

    Assigment files would contain thoroughly commented (with hints on how to continue) code structure with key pieces missing, the task usually was to “fill in the gaps”. A small (and usually incomplete) test suite was included, however students were encouraged to write their own more thorough tests.

    Running the application, tests, style checks and submitting finished assignments were all done with sbt. Upon submission assignments were automatically graded (usually within 10 minutes of submission).

    • Week 1: Recursion
    • Week 2: Functional Sets
    • Week 3: Object-Oriented Sets
    • Week 4: Huffman Coding
    • Week 5: no exercise this week, only videos
    • Week 6: Anagrams
    • Week 7: Bloxorz


    I enjoyed this course very much. At first I found it difficult to come up with recursive solutions, but within few weeks that got much easier.

    From the first week I was impressed how small functions were - usually less than 10 lines and probably none more than 15-20 lines of code.

    I’ve had quite a few AHA! moments when prof. Odersky described some Scala features. For example pattern matching just blew me away. I remember myself seeing a similar example, thinking “Holy ^$@%!” and not being able to sit down after so much excitement.

    trait Expr
    case class Number(n: Int) extends Expr
    case class Sum(e1: Expr, e2: Expr) extends Expr
    def eval(e: Expr): Int = e match {
        case Number(n) => n
        case Sum(e1, e2) => eval(e1) + eval(e2)

    Or that for expressions can be expressed in terms of map, flatMap and filter. Or how awesome Streams are.

    Another thing that I found interesting is the last assignment. The last assignment was a solver for a game called Bloxorz. Sure, it’s a simplified version of it (no orange tiles, circles or crosses), but fun nonetheless. It involved using streams to solve it.

    However, I have only one tiny problem with the course. That is I didn’t learn how to write Scala programs from scratch on my own. Having to write assignment programs from scratch would’ve been useful, but also (most likely) very difficult. A minor problem, that I managed to fix within few hours with online resources.

    Last thoughts

    Did I find it useful? Yes I did. Functional programming requires a different way of thinking and I can already see that it made an impact in how I write programs. And I find programming Scala very enjoyable.

    Would I recommend this course to you? Oh yes, definitely. It is an easy way to get familiar with functional programming and requires little time. In fact I myself have registered after reading many positive comments on Hacker News.

    If you want to take a look at it yourself, here’s the course website: Functional Programming Principles in Scala

    To learn more Scala I’m using it to solve Matasano Crypto Challenges, so if you’re interested in (learning) cryptography, check them out as well!

  • Memorising PI to 100 digits

    Currently the world record is 67890 digits, held by Lu Chao. According to some sources Akira Haraguchi has recited 100000 digits of PI, however the Guiness World Records have not accepted his record (Wikipedia).

    Memorising PI is rather fun and is a great mental exercise. The PI day was just 5 days ago (14th of March), so it’s a great occasion to start memorising.

    The technique

    Different people use different techniques to help them memorise PI, because each of us learns things a bit differently. There are three different learning styles: Visual, Auditory and Kinesthetic, thus different techniques will work for different learning styles. So you may find assigning numbers to musical notes, images or poems more effective.

    The idea of the technique I used is to divide PI into small blocks of numbers, which makes it easier to memorise. Divide and conquer!

    PI to 100 digits is: 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679

    • Start by copying the whole number into any text editor (e.g. Microsoft Word, Notepad, Google Docs)
    • Read through the digits. You should naturally start grouping them into blocks. Whenever you form a new block put spaces on both sides of the block to separate it from other blocks.

    Blocks may not be obvious at first, but once you start trying to memorise them, they should become much clearer.

    In the end, you should have something like this:

    1. 1415 92 6535 8979 323 84626 433 83 279 50288 4197 169399 37510 5820 9749 4459 230 781 640 628 620 8998 628 034 825 342 117 0679

    As you can see, the blocks I’ve chosen range from 2 to 6 digits in length. Yours may or may not differ - see for yourself what works for you.

    Now take blocks one by one and try to memorize them in order .

    I found memorising a few blocks at a time easier. By the way, sheer repetition really helps, though it probably wouldn’t work on longer sequences.

    Useful resources

    • Assigning digits to notes by Vihart - Youtube link
    • Link and Major systems - Link
    • Phonetic System - Link