0f > Float.MIN_VALUE = false!

Updates:
Turns out that this is the expected behaviour from the java doc:
A constant holding the smallest positive nonzero value of type float, 2-149.

So now, how do I get the smallest negative value that a float can hold?


Just came across the most weirdest thing ever in Java – 0f > Float.MIN_VALUE returns false!

Similarly, anything less than 0, (say -10 for example) is surprisingly not greater than Float.MIN_VALUE.

However, 0 > Integer.MIN_VALUE returns true!

Want to try it out?

public class E {
    public static void main(String[] args) {
        System.out.println("1f > Float.MIN_VALUE: " + (1f > Float.MIN_VALUE));
        System.out.println("0f > Float.MIN_VALUE: " + (0f > Float.MIN_VALUE));
        System.out.println("-1f > Float.MIN_VALUE: " + (-1f > Float.MIN_VALUE));
        System.out.println("0f < Float.MIN_VALUE: " + (0f < Float.MIN_VALUE));
        System.out.println("0f == Float.MIN_VALUE: " + (0f == Float.MIN_VALUE));
    }
}

Result:

1f > Float.MIN_VALUE: true
0f > Float.MIN_VALUE: false
-1f > Float.MIN_VALUE: false
0f < Float.MIN_VALUE: true
0f == Float.MIN_VALUE: false

MPU 6050 and it’s DMP over time

Using Jeff’s brilliant library for using the DMP on the MPU 6050, here are graphs of the DMP filling the FIFO buffer at 200 Hz, 100 Hz, and 50 Hz.

At 200 Hz, I found that while the MPU did interrupt my Arduino Due at 200 Hz, I could only read off the FIFO at 150 Hz. It overflowed twice or thrice every second. To be sure, I used the examples from the library itself.

In the graphs below, red is yaw, green is pitch, and blue is roll (time in seconds is on the x-axis, and the values are on the y-axis).
The MPU was kept on steady on the floor at all times during this test.

FIFO rate at 200 Hz:

MPU 6050 at 200 Hz

It’s unbelievably unstable. The values randomly shoot to 50 – 70 and stay there for a while. Before the MPU gives away (it doesn’t fill the FIFO for over 100ms), it’s about 17 minutes.

FIFO rate at 100 Hz:

MPU 6050 at 100 Hz
The values look stable enough for use. It’s just 6 minutes before the MPU gives away this time.

FIFO rate at 50 Hz:

MPU 6050 at 50 Hz
At 50 Hz, the values are very good. They stabilise within 10 seconds. However, the MPU stops filling the FIFO buffer after about 36 minutes.

Does anybody know what’s wrong here?

Arduino Due – Absolute Maximum Ratings

The table below lists the maximum current which can be sourced or sinked for a given pin on an Arduino Due board:

Due Pin Number SAM3X Pin Name Mapped Pin Name IOH (or ISOURCE) in mA IOL (or ISINK) in mA
0 PA8 RX0 3 6
1 PA9 TX0 15 9
2 PB25 Digital Pin 2 3 6
3 PC28 Digital Pin 3 15 9
4 connected to both PA29 and PC26 Digital Pin 4 15 9
5 PC25 Digital Pin 5 15 9
6 PC24 Digital Pin 6 15 9
7 PC23 Digital Pin 7 15 9
8 PC22 Digital Pin 8 15 9
9 PC21 Digital Pin 9 15 9
10 connected to both PA28 and PC29 Digital Pin 10 15 9
11 PD7 Digital Pin 11 15 9
12 PD8 Digital Pin 12 15 9
13 PB27 Digital Pin 13 / Amber LED “L” 3 6
14 PD4 TX3 15 9
15 PD5 RX3 15 9
16 PA13 TX2 3 6
17 PA12 RX2 3 6
18 PA11 TX1 3 6
19 PA10 RX1 3 6
20 PB12 SDA 3 6
21 PB13 SCL 3 6
22 PB26 Digital Pin 22 3 6
23 PA14 Digital Pin 23 15 9
24 PA15 Digital Pin 24 15 9
25 PD0 Digital Pin 25 15 9
26 PD1 Digital pin 26 15 9
27 PD2 Digital Pin 27 15 9
28 PD3 Digital Pin 28 15 9
29 PD6 Digital Pin 29 15 9
30 PD9 Digital Pin 30 15 9
31 PA7 Digital Pin 31 15 9
32 PD10 Digital Pin 32 15 9
33 PC1 Digital Pin 33 15 9
34 PC2 Digital Pin 34 15 9
35 PC3 Digital Pin 35 15 9
36 PC4 Digital Pin 36 15 9
37 PC5 Digital Pin 37 15 9
38 PC6 Digital Pin 38 15 9
39 PC7 Digital Pin 39 15 9
40 PC8 Digital Pin 40 15 9
41 PC9 Digital Pin 41 15 9
42 PA19 Digital Pin 42 15 9
43 PA20 Digital Pin 43 3 6
44 PC19 Digital Pin 44 15 9
45 PC18 Digital Pin 45 15 9
46 PC17 Digital Pin 46 15 9
47 PC16 Digital Pin 47 15 9
48 PC15 Digital Pin 48 15 9
49 PC14 Digital Pin 49 15 9
50 PC13 Digital Pin 50 15 9
51 PC12 Digital Pin 51 15 9
52 PB21 Digital Pin 52 3 6
53 PB14 Digital Pin 53 15 9
54 PA16 Analog In 0 3 6
55 PA24 Analog In 1 3 6
56 PA23 Analog In 2 3 6
57 PA22 Analog In 3 3 6
58 PA6 Analog In 4 3 6
59 PA4 Analog In 5 3 6
60 PA3 Analog In 6 3 6
61 PA2 Analog In 7 3 6
62 PB17 Analog In 8 3 6
63 PB18 Analog In 9 3 6
64 PB19 Analog In 10 3 6
65 PB20 Analog In 11 3 6
66 PB15 DAC0 3 6
67 PB16 DAC1 3 6
68 PA1 CANRX 3 6
69 PA0 CANTX 15 9
70 PA17 SDA1 3 6
71 PA18 SCL2 15 9
72 PC30 LED “RX” 15 9
73 PA21 LED “TX” 3 6
74 PA25 (MISO) 15 9
75 PA26 (MOSI) 15 9
76 PA27 (SCLK) 15 9
77 PA28 (NPCS0) 15 9
78 PB23 (unconnected) 15 9
USB PB11 ID 15 9
USB PB10 VBOF 15 9

References:

  1. Arduino Due – Pin Mapping for SAM3X
  2. Arduino Due – Broad Specifications
  3. SAM3X datasheet

Note: The ratings are on pages 1390 through 1392 of the datasheet for the SAM3X.

Thanks to the folks at the Arduino IRC channel(#arduino on freenode) for pointing me in the right direction!

A Usable Mac: Yosemite + Reduced Transparency + Lucida Grande

I updated to OS X 10.10 after a day it was released – only to be stunned by the really, really ugly looking UI. @francispereira dubs this new update as “Polio infected”. There’s transparency where it should never have been in the first place, and the font smoothing engine is gone haywire with the new system default font, Helvetica.

Let’s fix it:

Drop the transparency

Open System Preferences(type sys in Spotlight). Open the Accessibility settings(second last row, extreme right). Check the checkbox that says “Reduce transparency”.

Revert the system default font to Lucida Grande(the font used in OS X 10.9 and earlier)

Download this app which I found here. Uncompress the downloaded file, then right click on the extracted app, and click on Open. Then click on the Patch and Install button in the dialog box that appears. It will then prompt you for your system password, as it copies Lucida Grande from /System/Library/Fonts to /Library/Fonts, and then patches it to be the system default font.

Next, log out and log back in to see a more usable Mac.

Seriously Tim, you ought to check yourself before you wreck yourself.

Download your Coursera lectures using JS, bash and wget

So, in light of recent events, I was unable to follow up on my Coursera Algorithms course.

Trying to find a way to download all the lectures at once, I couldn’t find a way that worked for me – I found two, but they simply didn’t work. With the help of some JavaScript that I got from one of these sources, I cooked up the following steps to easily download all the lectures at once:

Step 1: Extract the lecture names, and their IDs from the Coursera page
Navigate to your lecture page(for me, it was https://class.coursera.org/algs4partII-003/lecture).
Execute the following JavaScript in the Console(in Chrome, use the Inspect Element option):

function findLectures () {
  var link_elems = document.querySelectorAll('.lecture-link');
  var lectures = "";
  Array.prototype.slice.call(link_elems).forEach(function (elem, i) {
    var lecture = i + "|" + elem.getAttribute('data-lecture-id') + "|" + elem.innerText.trim();
    lectures += lecture + "\n";
  });
  return lectures;
}

Then call the method findLectures(). This will print each lecture in the following format: Lecture position in page|Lecture ID|Lecture name.
Example output:

0|43|Course Introduction (9:22)
1|1|Introduction to Graphs (9:32)
2|2|Graph API (14:47)

Save this to a file named lectures.txt(exclude any quotes that get pasted)

Step 2: Export Coursera’s cookies
Use the Chrome plugin cookie.txt export to export all the cookies that Coursera has saved. Save the result to a file named cookies.txt

Step 3: Download them!
Run the following in the terminal:

export COUNT=1; while read line; do lecture_name=`echo $line | awk -F '|' {'print $3'}` lecture_id=`echo $line | awk -F '|' {'print $2'}`; echo "Downloading lecture $COUNT; ID=$lecture_id; Name=$lecture_name..."; ((COUNT++)); wget --load-cookies cookies.txt https://class.coursera.org/algs4partII-003/lecture/download.mp4?lecture_id=$lecture_id -O "$COUNT - $lecture_name"; done < lectures.txt

Make sure you replace the link to where your lectures are listed. The above link has “https://class.coursera.org/algs4partII-003/lecture/” in it.

This will download all the lectures in the current working directory. It does not maintain any relationship with the week that the lecture was released in. It downloads them in the order that they are listed on the Coursera lecture page.

“The Library” is here

“The Library” is a collection of several popular encyclopedias. It is your one stop for popular game guides and TV show trivia. You can search, and bookmark articles from various encyclopedias.
What’s more? Each time the app is launched, it displays a random featured article from the encyclopedia you last viewed! Explore more about your favourite game/TV show each day.

Popular encyclopedias include:
– Doctor Who
– Assassin’s Creed
– Lord of the Rings
– Mass Effect
– and 42 more!

With this app, you can:
– Read more about your favourite character
– Read about movie plots, and further details
– Game level guides and walk-throughs
– and much more!

Get it on Google Play

CardBox – Personalize a card for every occasion

We[the CardBox developers], have recently launched a brand new app, CardBox, which allows you to create and instantly share greeting cards for almost any occasion!
CardBox allows you to create cards for the following occasions currently:

  • Birthdays
  • Anniversaries
  • Christmas
  • New Year’s day
  • Valentine’s day
  • Women’s day
  • Mother’s day
  • Father’s day
  • Parents’ day
  • Grandparents’ day
  • Halloween
  • Children’s day
  • Thanksgiving

Here’s a review from one of our fans:

Creating personalized cards has never been this easy! Be it Christmas or New Year's or birthdays and anniversary wishes, CardBox allows you to custom make your own cute little e-card to send to the world. The app contains a bunch of ready-made cards to use for popular events. You can personalize these by adding in your own text and images. If you are more inclined towards the do-it-yourself cards, you can make your own from scratch as well, with the option to use your own photos, and the tons of font and color options available. One of the features that I appreciate most about CardBox is that it auto-syncs with your Facebook friends' information and sends you reminders of their life events such as birthdays and anniversaries. On the whole, this is a great little app to have just to wish someone on their special day in a very different way.

– Rashmi Anand

Like CardBox on Facebook

Get it on Google Play
Coming soon to iOS.

How to get a File object of an Android raw resource using reflection

Context:

You have a URI to a resource which is placed in the raw directory inside the Android resources directory, res. Say you want to take that raw resource(let’s say it’s an image) and add it to an attachment using FIleBody to a MultiPartEntity. Both these classes are available in the Apache HTTP Components library. FileBody will only allow you to give it a File object in it’s constructor. Certainly, you are stuck as you have the URI to an Android raw resource, and CANNOT create a File object out of it.

 

So what’s the solution? Reflection.

    private File getFileFromRawResource(Uri rUri) {
        String uri = rUri.toString();
        String fn;
        // I've only tested this with raw resources
        if (uri.contains("/raw/")) {
            // Try to get the resource name
            String[] parts = uri.split("/");
            fn = parts[parts.length - 1];
        } else {
            return null;
        }
        // Notice that I've hard-coded the file extension to .jpg
        // I was working with getting a File object of a JPEG image from my raw resources
        String dest = Environment.getExternalStorageDirectory() + "/image.jpg";
        try {
            // Use reflection to get resource ID of the raw resource
            // as we need to get an InputStream to it
            // getResources(),openRawResource() takes only a resource ID
            R.raw r = new R.raw();
            Field frame = R.raw.class.getDeclaredField(fn);
            frame.setAccessible(true);
            int id = (Integer) frame.get(r);
            // Get the InputStream
            InputStream inputStream = getResources().openRawResource(id);
            FileOutputStream fileOutputStream = new FileOutputStream(dest);
            // IOUtils is a class from Apache Commons IO
            // It writes an InputStream to an OutputStream
            IOUtils.copy(inputStream, fileOutputStream);
            fileOutputStream.close();
            return new File(dest);
        } catch (NoSuchFieldException e) {
            Log.e("MyApp", "NoSuchFieldException in getFileFromRawResource()");
        } catch (IllegalAccessException e) {
            Log.e("MyApp", "IllegalAccessException in getFileFromRawResource()");
        } catch (FileNotFoundException e) {
            Log.e("MyApp", "FileNotFoundException in getFileFromRawResource()");
        } catch (IOException e) {
            Log.e("MyApp", "IOException in getFileFromRawResource()");
        }
        return null;
    }    

The code is pretty much self-explanatory. Drop a comment if you have any questions/doubts.

Calculate the REAL scale factor and the angle of rotation from an Android Matrix

After performing transformations such as rotation of a bitmap about an arbitrary point, the scale is lost. Of course, this makes sense because the bitmap is rotated inside the same bounds.

To get the real scale now, along with the most reliable degree of rotation, I had to follow this method. Hope it saves the rest of you a night or two.

float[] v = new float[9];
matrix.getValues(v);
// translation is simple
float tx = v[Matrix.MTRANS_X];
float ty = v[Matrix.MTRANS_Y];

// calculate real scale
float scalex = values[Matrix.MSCALE_X];
float skewy = values[Matrix.MSKEW_Y];
float rScale = (float) Math.sqrt(scalex * scalex + skewy * skewy);

// calculate the degree of rotation
float rAngle = Math.round(Math.atan2(v[Matrix.MSKEW_X], v[Matrix.MSCALE_X]) * (180 / Math.PI));

Multi Touch in Android – Translate, Scale, and Rotate

Here’s a quick and easy implementation of Android’s multi touch feature – one finger to move, two to zoom, and three to rotate the image.

Assuming you have a basic understanding of 2D matrix transformations, the Matrix class in Android uses a 3×3 matrix to achieve all of the 2D transformations.

The source code and pre -built APK is available. See the end of this post.

Main activity – MultiTouch.java

package com.multitouch.example;

import android.app.Activity;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.os.Bundle;
import android.util.FloatMath;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;

public class MultiTouch extends Activity implements OnTouchListener {

    // these matrices will be used to move and zoom image
    private Matrix matrix = new Matrix();
    private Matrix savedMatrix = new Matrix();
    // we can be in one of these 3 states
    private static final int NONE = 0;
    private static final int DRAG = 1;
    private static final int ZOOM = 2;
    private int mode = NONE;
    // remember some things for zooming
    private PointF start = new PointF();
    private PointF mid = new PointF();
    private float oldDist = 1f;
    private float d = 0f;
    private float newRot = 0f;
    private float[] lastEvent = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ImageView view = (ImageView) findViewById(R.id.imageView);
        view.setOnTouchListener(this);
    }

    public boolean onTouch(View v, MotionEvent event) {
        // handle touch events here
        ImageView view = (ImageView) v;
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_DOWN:
                savedMatrix.set(matrix);
                start.set(event.getX(), event.getY());
                mode = DRAG;
                lastEvent = null;
                break;
            case MotionEvent.ACTION_POINTER_DOWN:
                oldDist = spacing(event);
                if (oldDist > 10f) {
                    savedMatrix.set(matrix);
                    midPoint(mid, event);
                    mode = ZOOM;
                }
                lastEvent = new float[4];
                lastEvent[0] = event.getX(0);
                lastEvent[1] = event.getX(1);
                lastEvent[2] = event.getY(0);
                lastEvent[3] = event.getY(1);
                d = rotation(event);
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_POINTER_UP:
                mode = NONE;
                lastEvent = null;
                break;
            case MotionEvent.ACTION_MOVE:
                if (mode == DRAG) {
                    matrix.set(savedMatrix);
                    float dx = event.getX() - start.x;
                    float dy = event.getY() - start.y;
                    matrix.postTranslate(dx, dy);
                } else if (mode == ZOOM) {
                    float newDist = spacing(event);
                    if (newDist > 10f) {
                        matrix.set(savedMatrix);
                        float scale = (newDist / oldDist);
                        matrix.postScale(scale, scale, mid.x, mid.y);
                    }
                    if (lastEvent != null && event.getPointerCount() == 3) {
                        newRot = rotation(event);
                        float r = newRot - d;
                        float[] values = new float[9];
                        matrix.getValues(values);
                        float tx = values[2];
                        float ty = values[5];
                        float sx = values[0];
                        float xc = (view.getWidth() / 2) * sx;
                        float yc = (view.getHeight() / 2) * sx;
                        matrix.postRotate(r, tx + xc, ty + yc);
                    }
                }
                break;
        }

        view.setImageMatrix(matrix);
        return true;
    }

    /**
     * Determine the space between the first two fingers
     */
    private float spacing(MotionEvent event) {
        float x = event.getX(0) - event.getX(1);
        float y = event.getY(0) - event.getY(1);
        return FloatMath.sqrt(x * x + y * y);
    }

    /**
     * Calculate the mid point of the first two fingers
     */
    private void midPoint(PointF point, MotionEvent event) {
        float x = event.getX(0) + event.getX(1);
        float y = event.getY(0) + event.getY(1);
        point.set(x / 2, y / 2);
    }

    /**
     * Calculate the degree to be rotated by.
     *
     * @param event
     * @return Degrees
     */
    private float rotation(MotionEvent event) {
        double delta_x = (event.getX(0) - event.getX(1));
        double delta_y = (event.getY(0) - event.getY(1));
        double radians = Math.atan2(delta_y, delta_x);
        return (float) Math.toDegrees(radians);
    }
}

An important function that is always used is postXx(). This function concats a new matrix of the type Xx to the existing matrix object. Using setXx() will reset the matrix’s Xx property.
Main layout – main.xml

<?xml version="1.0" encoding="utf-8"?>

<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<ImageView android:id="@+id/imageView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="@drawable/butterfly"
android:scaleType="matrix" />

</FrameLayout>

Browse and download the source code on GitHub.

Rooted? Get the most of your Android phone | A power saving strategy

The smart-phones these days are power hungry devices, and often drain the battery within six to eight hours, or even less. However, if it’s running Android, there’s a good chance that that can change. The key is to find the right set of tools, and optimize your phone to be right on the edge, there when you need it, and highly responsive. What it takes is a power saving strategy, offered by Set CPU for root users android application. This nifty little tool, worth it’s price, is by far the most essential application among several others(probably thousands). It allows you to set profiles, and depending on how well you set it up, you can extend your battery life by a couple of hours(~four).
So how do you balance phone responsiveness while saving power at the same time?
Take a look at the following two screenshots, it’s what I’ve got setup:

The settings indicated above, automatically scale the CPU frequency. The highest CPU frequency supported by your processor will take the most power, so if you’d want to scale it down, especially during low levels of battery, this application can help you do so automatically.
Read about the profile priority when setting up newer profiles for this application.

You can read about which CPU frequency governor is right for you here