Monday, January 25, 2016

Playing with Scala - 1

Being a programmer, whats point in not learning a language that is a bit complex than others?

Being Scala developer from almost 4 months now. I admire its compact logic building and strong syntactical shortcuts. I didn't dive much into its functional part, but I would like to share some of it also.
  1. It has so many flavors; programmers having background in C, C++, Java, Python get easily familiar with its syntax
  2. Object-oriented functional language; unlike Haskell and LISP - that are purely functional and Java - that is purely object oriented language, Scala is everything! All in one
  3. Salient features of Scala are nicely described here http://www.scala-lang.org/what-is-scala.html
  4. Runs on JVM so Java classes in Scala can be freely mixed
  5. Highly scalable; works from your desktop PC to a thousand nodes cluster i-e; Intel, Twitter and LinkedIn use Scala in their clusters
  6. Unlike Kotlin and Ceylon programming languages, Scala decided to make "better Java" instead of staying close to Java and ultimately improving almost nothing in it except syntactic sugar

Monday, January 11, 2016

A Few Lessons Learned From 2015

I tried to sum up my mistakes I did last year. Some of them were pretty dumb, others made me embarrassed to the point I took decision to never repeat them ever. Some of them made me proud. Some of them made me think what do I have to be proud of? Some of the key points, I learned, are mentioned below;
  1. Being yourself doesn't hurt you
  2. Hurting people hurts you eventually
  3. Don't sleep too much
  4. Productivity increases late-night (after 1am)
  5. Trustworthy people never ask you to trust them
  6. People who want to be in your life wouldn't stay shut about it
  7. Don't focus on peoples' interests more than you feel like you should
  8. Work quietly and let your work speak
  9. Read books in isolation and feel them
  10. Stay sharp and ready for attacks other frame for you
  11. Don't get framed in others' problems, be smart to judge your surroundings
  12. Don't offer to help if you can't do it honestly
  13. Don't listen to those who want to be listened and never listen to you
  14. Don't be gender biased in public or group talks
  15. Select a few words and make up your wit-dictionary and use it over and over again till you make habit of staying away from slang
  16. Dislike what you don't like but never dislike what others want you to dislike. There is always something beneficial for you what others suggest you to dislike
  17. Don't talk unless you have a strong reason
  18. Don't change yourself to comfort others

Thursday, December 10, 2015

CSV Reading Error (Python)

Just encountered a very ambiguous error in Python while reading a .csv file using the csv library in Python.

The solution made me feel pretty dumb. That is why I am blogging this to remember. From: https://docs.python.org/2/library/csv.html This is the code snippet I was trying to execute to read csv file at path /home/superuser/Desktop/day.csv.
import csv
with open('./day.csv', 'rb') as csvfile:
  r = csv.reader(csvfile, delimiter=' ', quotechar='|')
  for row in r:
    print ', '.join(row)
Python shell was showing error,
AttributeError: 'module' object has no attribute 'read'
Which made me thing that I'm importing wrong csv library. May be this import csv isn't importing the correct CSV I need. I was correct.
But the solution was pretty awkward. I was saving my file as "csv.py" and my program "csv.py" itself was importing itself.
Renaming the script to some other name resolved this issue.
Thanks to bernie's answer here:
http://stackoverflow.com/questions/9711799/csv-module-attributeerror

Thursday, December 3, 2015

Raspbian on Raspberry Pi 2

Following are the steps you need to know before installation of Raspbian - a distribution of Linux for Raspberry Pi 2.
  1. Download image of Raspbian from https://www.raspberrypi.org/downloads/
  2. Linux
    If you are using Linux/Unix, you need to burn (copy contents from) this image file (.img) into the SD card using following sequence of commands,

    df -h

    To check the list of all the drives mounted into system. Figure out from this list what is the name of your device mounted into /dev/device_name. This device name usually ends with p0, p1 and so on, which indicates the partition indexing. Make sure your card has one partition, at the time of installation and configuration of Raspbian, it automatically partitions into necessary parts.

    Easiest way to figure out what is the newly mounted SD card name in /dev/*, simply df -h before mounting SD card into PC, and then plug and find the newly plugged entry record from df -h output.

    Make sure you unmount the card before burning image into it, by using

    umount /dev/

    Run following command

    sudo dd bs=1M if=[DISK IMAGE NAME] of=[FILESYSTEM]


    Here, in bs=1M means the size of read and write of the bytes at a time equals to 1 mega. Sometimes 1M works while burning the SD card. If this doesn't work for your SD card, try using 4M or some other sector size.
    Wait for a while and your card will be burned with OS.

    Windows
    Use Win32 Disk Imager software to burn the SD card .img.
  3. Plug SD card into Raspberry Pi and plug it to 5V power, plug LED on HDMI port, keyboard and mouse on USB ports
  4. You will be logged in to Raspbian
    Default username password combination is pi and raspberry respectively
  5. You can expand storage by using raspi-config on terminal after you log in to LDX

Monday, November 30, 2015

Display Bits of an Integer

To display bits of an integer you have to check each and every bit so if I have an integer i = 12, it has binary representation 0000 0000 0000 0000 0000 0000 0000 1100.

Lets do it with C++ code. C++ provides bitwise operators for but twiddling, you can simply perform bitwise OR, AND, XOR and other operations like bit shifting using builtin operators.

To check single bit of integer on bit level you need to access each of 32 bits in integer. This is achievable using & operator. & operator has property, the result comes 1 by applying it with two operand bits only if the two bits are 1.

This & is applied to all the bits individually in integer and answer is computed in form of another integer. So if you apply & operation between 2 and 3.

2 = 0000 0000 0000 0000 0000 0000 0000 0010
    &&&& &&&& &&&& &&&& &&&& &&&& &&&& &&&&
3 = 0000 0000 0000 0000 0000 0000 0000 0011
-------------------------------------------
2 = 0000 0000 0000 0000 0000 0000 0000 0010

By using same logic, we can create a mask to check if each bit is zero or 1. If mask is set to 1 and later on shifted on left on each bit check some of the mask check for a 4 bit number iterations are like 0001, 0010, 0100, 1000. So after 4 left shift operations and performing & operation on original number, this mask goes zero, which can be used as loop termination condition.

Non-recursive Solution in C++

    int number = 12, mask = 1;
    while (mask > 0) {
        if ((number & mask) == mask)
            cout << 1;
        else
            cout << 0;
        mask <<= 1;
    }


But there is an issue with this code, bit pattern will be printed in reverse.

    int number = 12, mask = 1;
    stack s;
    while (mask > 0) {
        if ((number & mask) == mask)
            s.push('1');
        else 

            s.push('0');
 
        mask <<= 1;
    }


    // print elements in stack

This way the bit pattern will be displayed correctly.

There is another efficient way to print in correct order by using an unsigned integer.

For this, consider the following code,

    int number = 12;
    unsigned int mask = INT_MAX + 1;

    while (mask > 0) {

        if ((number & mask) == mask)
            cout << 1;
        else

            cout << 0;
      

        mask >>= 1
    }

Now, INT_MAX gives 2,147,483,647 and by adding 1 to it make it equal to 2,147,483,648 that is equal to 2 ^ 31. That means the 32nd bit of the mask will be ON. Shifting it to the right till it becomes zero and performing & operation prints correct bit pattern of integer.

Note: INT_MAX is present in climit header file.

Recursive Solution in C++

void displayBitwise(int num, int mask = 1) {
    if (mask == 0) return;

    displayBitwise(num, mask << 1, ++count);
    cout << ((num & mask) ? 1 : 0);
}


To make this bit pattern more readable, make chunks by separating by space,

void displayBitwise(int num,
                    int mask = 1,
                    int count = 0) {
    if (mask == 0) return;

    displayBitwise(num, mask << 1, ++count);

    if (count != 32 && count % 4 == 0) cout << ' ';
    cout << ((num & mask) ? 1 : 0);
}


Here if count != 32 isn't checked, space will be printed after first backtrack call. count % 4 == 0 prints a space after every four characters. Good luck!

Friday, November 20, 2015

شگفتہ لوگ

شگفتہ لوگ بھی ٹوٹے ہوے ہوتے ہیں اندر سے 
بہت روتے ہیں وہ جن کو لطیفے یاد رہتے ہیں

Thursday, November 5, 2015

An Achievement!

Working on some embedded system modules that aren't touched by anyone in opensource community is a real pain in the ass. A few days ago, I was chewing nails over some failures in work. Problems that become hard obstacles are milestones for me. I seek pleasure solving problems because when you get successful solving a problem, it becomes clear to you that problem of such difficulty level can be resolved. After solving a few different problem sets from different domains, you start realizing that nothing seems impossible to you anymore. That is the lesson I learned from the recent work I am doing.

Main focus these days is embedding communication protocols in Arduino Yun (cloud in Chinese). I was stuck embedding C/C++ libraries with Arduino. Because I wasn't seeing the real picture and wasn't considering the fact that Yun is technically more capable than Uno (Arduino board I was previously working with in my college days).

Problem

Real problem arose when I started looking at the system as an incapable machine and tried to put responsibilities on myself rather exposing full functionality of board itself.

I wasn't been able to embed C/C++ libraries into Yun.

One thing to be considered while working with Arduino is concept of library. A library in Arduino is not some sort of embed-able unit with the binary file that is to be deployed in it. In Arduino, library is just a bunch of classes providing functionality. Not like .dll/.so (dynamic) or .lib/.a (static library) in C/C++.

Solution

By using the Arduino Yun's Leonardo side (a linux-based processor) running kernel of OpenWRT (an opensource light-weight distribution for Yun), you can use all functionalities of Linux system (almost).

There are multiple languages support in Linino (OpenWRT) like Python, PHP5, Bash (not a language after all).

So you can simple run Python scripts using python compiler inside Arduino, run Bash scripts, run C programs using yun-gcc package.

Use make to Makefile projects.

Then, by using Bridge you can simply use these scripts that reside inside Linino by creating Process(es) and running them on your ATmega processor in sketch file programs.

Hi five!