Posts

    Monday, 16 March 2015

    A geek way to wish Happy Birthday!

    There is nothing more awesome than doing regular things in a geeky way. Few days back I was wondering what would be the geekiest way to wish someone happy birthday. It should be geeky alright, but should also have regular things like cake + candles + birthday song + wishing happy birthday.

    Now mixing all this with my very little knowledge in signal processing, I wrote a python code which does this:


    Fork me on github

    How it works?

    So, here we have a virtual cake who's shade has an equalizer effect corresponding to the "happy birthday" song that is played in the background. Here, the cake has candles with flames fluttering randomly. Also, we have a fancy display of happy birthday message.

    Lets see how each of it is done one by one.

    Equalizer effect

    The key here is to consider a sample size of frames in the audio corresponding to the part which is playing currently and display the normalized amplitudes inside the cake. First let's take a look at the amplitudes in the sound wave (stereo):

    Channel L:

    Channel R:

    As we can see even though the audio has two channels, both are nearly the same. Hence for further calculations we will discard one of the channels. If this was not the case, we should have taken the average of both the channels. If the audio file you have taken is already mono, you don't have to worry about anything.

    As there is no negative amplitude in the equalizer effect, we will make all values positive:

    Now that we have the required data, we can iterate over the frames and display the amplitudes in the cake to give equalizer effect. In the current example, I am considering 1500 frames per iteration. No matter how many frames you consider in a given iteration, the total time taken to complete the iteration should be same as the time required to play the song. Hence we add a sleep after every iteration. The net sleep time+processing time should be equal to song's play time.

    We can't display all the 1500 frames at a given time. Hence we take samples in that 1500 frames and averages of each sample is found. The averages are then normalized between the maximum and minimum amplitudes that can occur in the entire song. These normalized averages are then represented as a sequence of 8s (longer the sequence implies higher the amplitude). 

    Walah! you have the equalizer effect.

    There is a serious problem here. The time required for processing, printing on terminal and waking up from sleep are not determinable. For instance printing on xterm happens very fast whereas the mac terminal or gnome-terminal can be very slow. Hence we need to add a manual correction to the sleep time in order to stay in phase with the song which is being played.

    Fluttering candle flames

    If you observe the video, the candle flames can have three states:

    <space> <dot> <space>
    <space> <space> <dot>
    <dot> <space> <space>

    So basically we just have to randomly switch between these three states to get the fluttering candle flame effect.

    Happy birthday text

    I have used figlet to print the message. You can also display with different fonts and sizes.

    Python Code




    Enjoy!



      

    Sunday, 22 February 2015

    Magneto = Gyroscope + Accelerometer + Geomagnetometer

    I recently participated in a 24hr hackathon where I built a system called Magneto using which people with physical disabilities will be able to control a computer with arm movements and voice commands. This sort of gives the power of Magneto (from Xmen), hence the name!

    Magneto runs on both android phone and wear. Here is a quick view of its working:




    If you are interested to view the source. Github: Magneto

    The intention of this article is not to showcase Magneto, but to explain the physics behind how I was able to map the sensors on android device to mouse movement. While making it, I had used a lot of builtin functions and some help from FusedGyroscopeSensor. Later, I did a lot of research (mainly on linear algebra and rotation physics) to get a clear understanding of the logic. In this article I will clearly explain the learnings.

    Sensors

     I have used 3 sensors available on android device
    1. Accelerometer -  measures the acceleration applied to the device, including the force of gravity.
    2. Geo magnetic sensor - lets you monitor changes in the earth's magnetic field.
    3. Gyroscope - measures the rate or rotation in rad/s around a device's x, y, and z axis.

    Getting the initial rotation matrix

    The initial rotation matrix describes the initial orientation of the device. It is found using accelerometer (for gravity) and geomagnetic sensor. Any vector when multiplied with this rotation matrix should transform it to world coordinate system. This is an identity matrix if the device is aligned with world's coordinate system, that is, when the device's X axis points toward East, the Y axis points to the North Pole and the device is facing the sky.
    Device's coordinate system
    Step 1 Rotate geomagnetic vector (E) over gravity(g) using Rodrigues' rotation formula


    Now normalize the vector



    Step 2 Now normalize gravity vector




    Step 3 Rotate A over H using Rodrigues' rotation formula




    Step 4 The rotation matrix R is represented in terms of H, M and A



    Get current orientations using gyroscope

    Now that we have the initial rotation matrix we can proceed processing the rotations of the device. The gyroscope measures the rate or rotation (not normalized) around a device's x, y, and z axis i.e angular velocity. Also, we keep track of time taken for the device to rotate from its previous position to current position.

    Given that gyroscope works very fast, we can divide one action into several smaller samples in a sequence. Now let us consider one such smaller sample.
    Say the rates(angular velocity) and time taken are:





     "In three-dimensional space, any displacement of a rigid body such that a point on the rigid body remains fixed, is equivalent to a single rotation about some axis that runs through the fixed point."

    It means that any rotation can be expressed as a single rotation about some axis. The axis is the unit vector which remains unchanged by the rotation. Let us determine this angle.

    Angular speed is calculated. It is just the magnitude of angular velocity.



    Angular velocity is normalized. The resultant vector gives us the unit vector in the direction of angular velocity. This is called Euler axis.



    Now that we have magnitude  of angular velocity we can calculate Euler angle.



    Rotation Vector is a 4 dimensional vector called quaternion represented in terms of Euler axis and angle[2] as follows:



    The delta rotation vector is converted to delta rotation matrix. Now, In order to get the resultant rotation matrix, the current rotation matrix is multiplied with the delta rotation matrix.



    Now actual angles i.e angles made by the device with respect to device's coordinates (NOT world coordinates) are determined. See Conversion formulae between formalisms.


    Mapping angles with mouse's coordinates

    Now that we have the required angles, we can determine the desired mouse coordinates. If D is the approximate distance of the device from monitor, D tan Î¸ will give its component on the monitor. Using this concept we can find out the desired X and Y coordinates  of the mouse.




    Repeat this process (except finding initial rotation matrix of course) every time the device moves to determine mouse coordinates.


    NOTE: All formulae were made using Latex and are shared here for your use :)

    Sources:
    [4] Android SDK - SensorManager.java





    Wednesday, 21 January 2015

    WhatsApp Web desktop client for mac


    Whatsapp Messenger finally enabled users to use it from desktop. Unfortunately it is not a desktop client and you have to open the browser all the time to open it. Safari lovers have to open Google Chrome just to open WhatsApp! So I created an unofficial desktop app for mac using which you can get a standalone desktop experience while using it.


    Installing

    Firstly I am assuming that you have installed chrome browser. This will be a wrapper application around Google Chrome. Download the zip file. Extract the zip and simply double click on Whatsapp.app to open it! You can also move it to Applications folder to access it from anywhere. This is how it looks.

    Download WhatsApp for Mac



    How it works

    If you want to make the app yourself, Simply execute the following shell script!


    Now simply open the app!

    Saturday, 17 January 2015

    How to use youtube-dl on android

    There are hundreds of apps on Google Play which claim to download youtube videos. However most of them are either fake or not functional. Youtube recently added a feature using which it is possible to download youtube videos. But it stores it only for two days.
    We all know that youtube-dl provides us a 100% effective way to download videos from youtube. In this post I will show you how to do this:

    Step1

    Install python. See this Installing python on Android.

    Step2

    Download and transfer youtube-dl to your phone (you can do this directly on your phone if you don't have adb)


    Then open terminal on your android device and do this:


    Now you can easily download youtube videos using youtube-dl from terminal!!


    Monday, 12 January 2015

    How to use TP-LINK router to boost your network

    Do you have a spare router which you are not using? It is possible to use it to boost the network coverage of your existing WiFi by using it as a repeater! In this post I will show you how to use T-LINK WR740N router as a repeater to boost your network.

    Step1

    Connect your computer to router using a LAN cable. Open your route's admin page. It is either http://tplinklogin.net or 192.168.1.1. Then login with your credentials (default details are given at the back of your router).

    Step2 

    Now you will be shown the admin page of your router. Go to Wireless -> Wireless Settings. Check Enable WDS Bridging.


    Step 3

    Now enter the name(SSID) of the network of the main router (the one you want to boost). Then click on Survey button.


    Step 4

    Now click on the connect link corresponding to your main router.



    Step 5

    Now select the appropriate Key type, password and other security details of the main router. Note that Key type is usually WPA-PSK/WPA2-PSK and the options WEP Index and Auth type are not required.  Then click Save.



    Step 6

    Now the following text appears:

    The change of wireless config will not take effect until the Router reboots, please click here to reboot.

    Click on click here to reboot

    Step 7

    Now, similar to the way you logged in to the secondary router, login to the main router's admin page and disable DHCP and restart it.  You are good to go!

    Saturday, 3 January 2015

    Installing python on Android 5.0

    Executables with PIE (Position Independent Execution) have been supported since Android 4.1. It is a security feature involving address space layout randomization(ASLR) to prevent attacks such as buffer overflow. In Android's latest release Lollipop, PIE has been made a requirement. Similar to the way the shift from Dalvik to ART has crippled so many applications, this move has caused a lot of problems to developers.  Even some of the binaries shipped with android itself were broken because of this.

    I will be showing you how to install RunPythonFromShell. If you have already installed it and want to see how to bypass PIE go to the section Bypassing PIE.

    Step 1

    Download apk

    Install the apk and open it. Click the install button in the app to install all the modules and binaries.

    Step 2 

    If you don't want to run python from everywhere, skip this step. 
    • Open adb shell
    • Download the following gist. Move it to /system/bin and change set executable permission.
    • If you are running an android version older than lollipop then you are done! Lollipop users have to bypass PIE.

    Bypassing PIE

    Due to the PIE restrictions you get the following error when you run python:
              
             error: only position independent executables (PIE) are supported.

     The idea here is to replace the default linker with a custom linker (You need a rooted device. duh!).  First mount /system in write mode and backup the default linker.

    mount -o remount,rw /system /system
    mv /system/bin/linker /system/bin/linker.old

    Download custom linker

    Move custom linker to /system/bin. Then set proper permissions.

    chmod 0755 /system/bin/linker

    You can also use ES File Explorer or Root Explorer to do this. Permission of the file should look like this:

    You are done! You can run python from terminal!


    I will be writing a post on what all cool things you can do with python on android. Stay tuned! 

    Update

    Some of the users with 64 bit architecture were facing some linking problem. Here is what you have to do.
    Create a new lib64 directory and move the library file to that folder.

    mkdir /data/data/com.googlecode.pythonforandroid/files/python/lib64
    cp /usr/lib64/libcrypto.so   /data/data/com.googlecode.pythonforandroid/files/python/lib64

    Then you have to add this to the library path. To do that you have to update the variable LD_LIBRARY_PATH in the "/system/bin/python" script above.


    Thanks Yan Bellavance for pointing it out!

    Wednesday, 24 December 2014

    Add Exchange account to Gmail 5.0 on older android versions

    I installed unofficial CM 12 with Android 5.0.2 today. Earlier I was using stock Android Lollipop and it had the option of adding Microsoft Exchange account. Unfortunately CM12 didn't seem to have it.

    After doing some research I figured out that only devices running stock Android 5.0+ are capable of having exchange accounts. And CM12 although runs on Android 5.0, doesn't have this feature. On doing further research I found out that Android 5.0+ have something called Exchange services which enables gmail 5.0 to handle exchange accounts.

    Download Exchange Services


    Then, install and restart your device. Walah! Gmail will be able to add exchange accounts!

    Note: This method is not just for CM

    Friday, 5 December 2014

    How I fixed bootloop on my Nexus without loosing data

    I was playing around with framework-res.apk and SystemUI.apk to get Ambient Display on my Nexus 4. When I restarted my phone, it seemed to have stuck in a bootloop. I knew that factory reset might've worked. But I didn't want to lose any data.

    Fortunately adb was working. When I did adb logcat , it was logging an error saying:
     /system/framework/framework-res.apk is neither a file nor a folder (type=0)

    I realized that there was some problem with permissions of that file. I used adb shell and changed the permission of framework-res.apk and SystemUI.apk to 0644. But this was of no use. However I came to know that if I could somehow reset /system partition the problem would be solved.


    • So I downloaded the factory image of my phone. For nexus devices it is available here
    • Extract the contents of the image-xxxx-xxxx.zip to get the file system.img.
    • Then ran the following:
      adb reboot bootloader
      fastboot flash system system.img
    • This will wipe the /system partition and reset it without touching any other partitions. Hence you will not lose any data.
    • Restart. It took a while to start the phone completely. But it solved the problem!
    This is how I was able to reset my framework-res.apk and SystemUI.apk!


    Monday, 24 November 2014

    Type checking in javascript has never been easier

    I love languages which aren't strongly typed. It makes software development process very fast and very easy as we need not write huge, complex, unreadable code like in our typed languages. However this can lead to developer's worst nightmare: Runtime errors! In languages such as javascript it is not easy to check for type mismatches while in development process. Hence flow was invented!

    Flow is one of Facebook's open source projects. It allows developers to check for programming errors in javascript code with very less effort. This is a sample code available on their site:

    function foo(x) {
      return x * 10;
    }
    foo('Hello, world!');

    Note that a string is passed into the function foo and an arithmetic operation is performed on that string inside it. When flow is run on this code:

    01_HelloWorld/hello.js:7:5,17: string
    This type is incompatible with
      01_HelloWorld/hello.js:4:10,13: number

    It points out that the string is incompatible with number. Consider a much much complex code. An error like this can simply be unnoticed until a runtime error is raised.

    Source: https://github.com/facebook/flow
    Installation: http://flowtype.org/docs/getting-started.html
    Examples: http://flowtype.org/docs/five-simple-examples.html

    Sunday, 23 November 2014

    Navigation Bar suddenly disappeared on Nexus

    This can happen on any phone with soft navigation keys.

    Yesterday, I was tweaking my Nexus 4 after updating to Lollipop. When I restarted my phone I found that the Navigation Bar had disappeared! Even to switch from one app to another I had to restart my phone! Then I found a way to fix it.

    Install Root explorer or ES Explorer. Open it and go to /system and mount it in R/W.

    Then open the file build.prop in the current folder using text editor.

    Then go to bottom of the file and change the value of "qemu.hw.mainkeys" from 1 to 0
    Reboot and you are done!