Tuesday, September 13, 2011

CDT Indexer & Google gtest framework

As I mentioned in a previous post of mine, Eclipse's CDT (C++ Development Tools) has a few issues when used with Google C++ Unit Testing framework, but it generally works.

Where CDT really gets confused is around the 'exclusion' of the unit tests for the non-test build configurations: as mentioned in my other post, one needs to add the G-Test's include/ directory to include search path (-I).

This blog has now been moved to codetrips.com: read the rest of this post here.

Tuesday, September 6, 2011

Android ADK and mbed.org



The 'mbed kit' just landed on my doorstep, sent courtesy of the good guys at ARM (Cambridge, UK).
This gadget supports the Android ADK (http://mbed.org/cookbook/mbed-with-Android-ADK)
which is fully documented here and, to have an idea of the geeky-fun that can be had with these gizmos, I suggest you check out this video.
I fear that my weekends are likely gone for quite a while now....


Just as an example of what is possible, the following snippet will make the LEDs flash, as well as connect to a terminal on the host PC to use as stdout; this is a very basic adaption of the HelloWorld.cpp app, and some tutorials from mbed.org: the point being that it took me less than 30min to get going!

// AlertAvert.com (c) 2011. All rights reserved
//
// The code below has been adapted from tutorials on
// mbed.org - credits should go to ARM Ltd.
//
// Author: M. Massenzio (m.massenzio@gmail.com)

#include "mbed.h"

// USB out to the host PC - from a terminal window access
// using: screen /dev/ttyACM0
Serial pc(USBTX, USBRX); // tx, rx

// Board LEDs
DigitalOut myled(LED1);
DigitalOut yourled(LED2);

bool on = true;
void quit() {
  on = false;
}

void toggle(DigitalOut d1, DigitalOut d2) {
  d1 = !d1;
  d2 = !d2;
}

int main() {
  pc.printf("Starting LED flashing...\r\n");
  Timeout to;
  myled = !(yourled = 1);
  to.attach(&quit, 5);
  while(on) {
    toggle(myled, yourled);
    wait(0.2);
  }
  myled = yourled = 0;
  pc.printf("Exiting now\r\n");
}


And this is what came out of it:

Monday, August 22, 2011

Use a common Tag for all your activities' logging

It is pretty common for any non-trivial Android app to be composed of several Activities which together interact with the user for the furtherance of whatever is the objective of the app itself.


It is also pretty common, especially during the development phase, to have a need to emit logs so that one can check certain events happen when they are supposed to, and invariants, for example, are satisfied.


The Android ADT (Eclipse plugin) has a very nice feature in the form of the LogCat View that shows all the system logs, including those coming from your applications: as there may well be tens of apps running (and logging) at the same time (especially on a live device -- as to why you should use a device for your testing and debugging, you may want to read this) the LogCat enables one to 'filter in' a subset, based on a 'tag'.


The tag used by the LogCat is the value of the string used for the tag parameter in the Log.x() calls:
Log.d("myApp.tag", "All is going well");

It is pretty obvious that, in any given Activity, we would want a constant to use as the tag:
private static final String TAG = "myApp.tag";
but this has the drawback that we would have to either duplicate that same statment across all Activities (and, even worse, keep them all in sync if we decide, for whatever reason to change them) or resign ourselves to use different tags for different activities.


Alternatively, we could use a common 'Constants' class to keep, amongst others, a constant Tag:
public interface Constants {
  public static final String TAG = "myApp.tag";
  // other constants...
}

This is not very friendly, however, as every log statement (and there may well be hundreds in your code) would look something like:
Log(Constants.TAG, "All is going well");
it's only 10 extra characters, but multiply that for several hundrends, and you've a veritable case of carpal tunnel syndrome on your hands (well, ok...).

A much better option is to use Android's mechanism to store common application strings, which also gives the additional benefit that it's dead easy to change the tag in one full swoop, should that ever be necessary: in one of the XML files in the res/values/ directory, have a line of the form
myApp.tag
and in your code, you can do something like:

public class MyActivity extends Activity {
  public static String TAG; // note no 'final' here

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    TAG = getResources().getString(R.string.TAG);
    Log.d(TAG, "Starting User Preferences activity...");
    // other initialization follows...
  }
}

This can be done in each and every of your App's activities, and then you can easily create a new filtered view in LogCat so that you can see only your App's logs, from all the activities, also with the reassurance that, should ever want to change that, it's just a one minute edit of the XML file


Saturday, August 13, 2011

HTTP POST for Android (with a twist: Protocol Buffers)

One of this blog's most visited entries (ranking always around the Top 5 Google results for "HTTP POST" too) elaborated on how to send data across to a server from a J2ME Midlet.


I thought it was high time for bringing this into the new Century, and provide an update as to how to do this from an Android smartphone.
It turns out that (a) the code is relatively straightforward and (b) that there is not so much difference after all from writing the same code for a desktop client: credit for this ought to go to the Android Google team who have done such a superb job of adapting the J2SE API to the Android platform...

THIS BLOG HAS MOVED TO codetrips.com


Please read the rest of this post on codetrips.com

Tuesday, August 9, 2011

Automating Eclipse launch

I've recently taken up the Eclipse team at Google (we integrate Google's internal build tools and distributed development environment with the Eclipse Platform) and we are constantly faced with the challenge of maintaining several distributions in a multi-user environment.


I thought I'd use some of the goodness we've come up with in my home environment too, so have put together a much-scaled-down version of our launch script, for my personal use - and thought I'd share this more broadly, as I'm sure other folks will find this useful too.


I generally have multiple installation and user configuration profiles, and even from the desktop launcher, I much prefer to use launch scripts than just pointing the shortcut to the binary executable.


Here is my generic configuration script:
#!/bin/bash
#
# Runs the stable version of Eclipse.
# By default, it will launch Indigo, installed in /opt/eclipse; different
# versions can be launched by invoking this script and setting the
# ECLIPSE_INSTALL and CONFIG variables to point to the correct places.
#
# The default configuration directory is set to '/home/$USER/.eclipse/eclipse37'
# but this can be changed exporting a different value for CONFIG.
# See /home/marco/bin/eclipse-helios for an example of how to do this.

##############################
# Globals (default value):
#
#   LD_LIBRARY_PATH           (/usr/local/lib:/usr/lib)
#     library search path for C++ dynamic libraries
#
#   ECLIPSE_INSTALL           ()
#     installation directory
#
#   CONFIG                    ()
#     user's configuration directory
#
#   MEM_ALLOC_POOL, PERM_SIZE (2,048MB, 256MB)
#     Memory allocation and PermGen size
#
#   JVM                       (/usr/local/java/bin/java)
#     Java VM executable (java)
#
# By setting any of the variables above after source`ing this script
# and before invoking launch_eclipse() the default value(s) can be changed
##############################
declare ECLIPSE_INSTALL
declare CONFIG
declare MEM_ALLOC_POOL
declare PERM_SIZE
declare JVM="/usr/local/java/bin/java"

##############################
# Concatenates input paramters to LD_LIBRARY_PATH, if not already present
##############################
munge_library_path() {
  for dir in $@; do
    if [ -n "${dir}" ]; then
      local is_present=`echo $LD_LIBRARY_PATH | grep ${dir} | wc -l`
      if [ ${is_present} -eq 0 ]; then
        export LD_LIBRARY_PATH=${dir}:$LD_LIBRARY_PATH
      fi
    fi
  done
}

##############################
# Sets up global variables with default values if not already set
##############################
check_dirs() {
  # Installation directory
  if [ -z "${ECLIPSE_INSTALL}" ]; then
    echo "You must set ECLIPSE_INSTALL to the Eclipse installation directory"
    exit -1
  fi
  if [ ! -d ${ECLIPSE_INSTALL} ]; then
    echo "Cannot find Eclipse installation directory (${ECLIPSE_INSTALL})"
    exit -1
  fi

  # Configuration directory, user-specific
  if [ ! -d "${CONFIG}" ]; then
    mkdir -p ${CONFIG}
  fi
}


##############################
# The location of the JVM, currently the default (OpenJDK 6)
##############################
locate_jvm() {
  if [ ! -e "${JVM}" ]; then
    echo "Could not locate a valid JVM at ${JVM}"
    echo "Trying to locate a valid java installation"
    JVM=`which java`
    if [ -z "${JVM}" ]; then
      echo "Could not find a valid JRE, giving up"
      return -1
    fi
    echo "Found a JRE at ${JVM}"
  fi
}

##############################
# Runs a few checks, sets up the LD library path and then launches Eclipse
#
# Param:
#   clean   will set the '-clean' Eclipse option that will clear the plugins cache
##############################
launch_eclipse() {
  check_dirs
  locate_jvm
  munge_library_path /usr/local/lib /usr/lib

  if [ "$1" == "clean" ]; then
    CLEAN="-clean"
  fi

  $ECLIPSE_INSTALL/eclipse $CLEAN -vm $JVM -configuration $CONFIG \
      -bundlepool $CONFIG/plugins \
      -vmargs -Xmx${MEM_ALLOC_POOL:-"2048M"} -XX:MaxPermSize=${PERM_SIZE:-"256M"}
}
This is used in the actual shell script (called, unimaginatively, eclipse):
#!/bin/bash
#
# Runs the stable version of Eclipse.
# By default, it will launch Indigo, installed in /opt/eclipse; different
# versions can be launched by invoking this script and setting the
# ECLIPSE_INSTALL and CONFIG variables to point to the correct places.
#
# See eclipse_config.sh for more details

source /home/marco/bin/eclipse_config.sh

ECLIPSE_INSTALL="/opt/eclipse"
CONFIG="/home/${USER}/.eclipse/eclipse37"

launch_eclipse


What is left is to just point a desktop (or menu) launcher to this script and replace the generic icon with the one in the eclipse/ folder (icon.xpm)




CREDITS -- I would very much like to gratefully acknowledge Machtelt Garrels and his much-consulted "Bash Guide for Beginners;" I never seem able to remember the bash conditional operators!

Wednesday, July 6, 2011

Eclipse (Indigo) Update site

When executing a "clean run" of Eclipse (typically, after p2 has completely messed up your installation and you've lost critical functionality / plugins -- the only reliable remedy I've found thus far, is to wipe ~/.eclipse, and restart from scratch) the 'Available Update Sites' is an empty list.


Googling the information proves every time a complete random shot in the dark, so I thought I'd collect the info once and for all in a place I'm likely to find again in the future.


The wiki page (impossibly difficult to find in the maze that Eclipse documentation is):
http://wiki.eclipse.org/Eclipse_Project_Update_Sites 


Gives this link for...
The Eclipse Project Updates - http://download.eclipse.org/eclipse/updates/3.7


Executing an update of the Eclipse Platform, adds another 'update site' that provides a much
richer selection of available plugins:


Indigo - http://download.eclipse.org/releases/indigo


Hope this helps someone else too!

Tuesday, May 24, 2011

Ubuntu: Network Manager is evil

Warning - this post if filled with hatred, if you believe in forgiveness, you may want to look away now.

In my book, the only sin worse than uselessness, is actively causing damage and waste of time.
What punishment ought to be meted then, to something that, having proven to be useless, causes untold waste of time.

Yes, NetworkManager, and nm-applet: I'm looking at you two.

Quite apart from never having quite understood what use one could have for either, I have found a number of situations in which NM has caused waste of time, only the last of which has been to prevent a KVM virtual machine I just created to connect to the network, despite all my efforts, searching on the Web, trying out countless variations on configurations and, yes, several reboots.

I have been following along the instructions given here, only to be unable to connect in UserMode, barely managing (via the Bridged interface) to connect to my host machine, and totally failing to obtain any connection to the outside world.

Enter

sudo apt-get purge network-manager network-manager-gnome

and, hey, presto, all is good and well, and I can happily connect from my guest OS to the Internet.
(see also here)

Simply changed my /etc/network/interfaces file to reflect my settings (YMMV, adjust to your LAN settings) and all works just fine:

auto lo
iface lo inet loopback

auto eth0
iface eth0 inet dhcp

auto br0
iface br0 inet static
        address 192.168.1.10
        network 192.168.1.0
        netmask 255.255.255.0
        broadcast 192.168.1.255
        gateway 192.168.1.1
        bridge_ports eth0
        bridge_stp off
        bridge_fd 0
        bridge_maxwait 0

Just remember to restart the network after you have made the changes:

sudo /etc/init.d/networking restart


Die in pain, Network Manager, and may the world be a better place without you.

Sunday, May 22, 2011

Creating a C++ callback function from a class instance method


I have been playing around with the Boost library and, in particular, the boost::thread multithreading library.


There a thread is simply created by constructing an object of type boost::thread, and passing in to the constructor a pointer to the function to be executed in the newly spawned thread.


There is much more to it, and I encourage you to read the documentation, but that gave me an interesting opportunity to ponder the issue of how to create a thread by instead passing in a pointer to a class's method: the need typically arises when one does not want to use global variables (which need to be guarded against race conditions) or where parameters are necessary for the execution of the method and/or return values are expected.


Granted, the boost::thread constructor allows you to pass in up to nine parameters, so that's rarely an issue, but I just wanted to find out a reasonably general way to achieve this; it turns out that this is far from trivial, and I thought I'd share my findings.


For the impatient, this is the solution:

template<typename T, typename V, typename R>
class MakeCallback {

  // Member method in T(ype), takes parameter V(alue),
  // and returns an object of type R(esult)
  // Note the parentheses around (T::*): without them, 
  // the compiler gets confused.
  typedef R(T::*func)(const V&);
  func f_;
  T& t_;
  V value_;
  R* res_;
public:
  MakeCallback(T& type, func f, const V& value, R* res = NULL) :
      f_(f), t_(type), value_(value), res_(res) { }
  virtual ~MakeCallback() { }
  void operator()() {
    if (res_)
      // Note here the parenthesis around t_.*f_ 
      // They are necessary, or a compiler error will be generated
      *res_ = (t_.*f_)(value_);
  }

  // This allows the pointer to the result value to
  // be set after the object has been created
  void set_res(R* res) { res_ = res; }
};

and this is how one uses it:

int main(int argc, char[}* argv) {
  A a(33);
  int res;
  // Generally, you don't need the & operator to take a function's pointer.
  // But in this case it's mandatory, or the compiler will complain
  // about doSomething() not being static.
  // In any event, the use of & makes your intent clearer (you are taking
  // the method's address,
  // not invoking it) and I encourage you to use it consistently, even where
  // this is not stricly necessary.
  MakeCallback<>A, int, int> mc(a, &A::doSomething, 22, &res);
  boost::thread do_it(mc);
  do_it.join();
  std::cout << "And the result is : " << res << std::endl;

  B b;
  boost::thread another(MakeCallback<A, std::string, B>(a, &A::doSomethingElse, "22.13", &b));
  another.join();
  std::cout << "..and B is " << b.get() << std::endl;
}
given the following declarations for A and B:
class B {
  float x;
public:
  B(float s = 0.0) : x(s) {}
  float get() { return x; }
};

class A {
  int num_;
public:
  A(int num) : num_(num) { }

  int doSomething(const int& k) {
    return num_ + k;
  }

  B doSomethingElse(const std::string& s) {
    double b = ::atof(s.c_str()) + num_;
    return B(b);
  }
};
A couple of points that have caused me much head-scratching and I thought it worth passing on:
  • you must use the '&' operator in front of A::doSomething, or the compiler will complain about it not being a static function;
  • note we are, in fact, calling an instance method: in other words, we expect to have instance-specific values stored in the class (A in this case) that our method (doSomething()) will use
  • note also the use of a pointer (R* res_) to store the return value: this is important; without it, the return value of the method call ((t_.*f_)(value_)) will be lost!


    This is because, in the call to boost::thread(mc) the compiler automatically created a copy of our object (using the compiler-generated copy constructor; see Scott Meyer's "Effective C++", Item 5)
  • Note also the calls to thread::join() - without them, you'd have a race on the returned values: possibly reading them, before the actual method (doSomething()) had any chance of updating it;
Just to be clear, this rather trivial implementation is not meant to be used in real code (if you need something along these lines, boost::bind is what you want) but it was an interesting exercise in how to deal with generics, functors and callbacks.

Sunday, May 8, 2011

Skype on Ubuntu 10.04 - mic doesn't work

I got the following fix from here, but it does not tell the entire story:
(my setup: Acer Aspire One AO751h,
Ubuntu Lucid 10.04.2 LTS)




  •  
    I had the same problem on an Acer Timeline for a long time, but the balance trick works.


    Solution:
    A better way than changing the output balance is to use alsamixer or pavucontrol and mute one of the input channels. In alsamixer: F4 to change to recording, left/right to move to microphone, and z or c to mute one channel. In pavucontrol go to the "input devices" tab, unlock the channels, and mute one of the channels.


    It seems the normal volume control uses one balance slider for all inputs and outputs together. 

    The reality is that two poorly designed (and worse implemented) pieces of software interact in a way to make it virtually impossible for the average user to figure out what's going on:

    • Pulse Audio -- it still amazes me how a simple problem (enable audio on a PC) could be made so complicated and unusable;
    • Skype for Linux -- a real disgrace that a company of the might and power of Skype could let us down so badly: I just wish they had the decency of release the software open source, so we could fix it ourselves!
    Be that as it may, in addition to the 'fix' above, you need to also disable the "Allow Skype to adjust mixer levels" in the Sound Options tab of Skype - otherwise you can see skype continually adjusting your microphone's gain down until it gets to the point of being unaudible.

    Leaving it here for future reference: I don't expect Skype to fix this anytime soon!

    Sunday, April 10, 2011

    Eclipse CDT and Google GTest

    If you have read my previous post about adding the gTest framework to your C++ project, you are very likely to have spent quite some time scratching your head trying to figure out how to make it play nicely with Eclipse's CDT, and its (let's face it) not terribly well-developed concept of 'Build Configurations'.


    THIS BLOG HAS MOVED TO codetrips.com

    Please read the rest of this post on codetrips.com

    Saturday, March 26, 2011

    Mobile templates






    Just enabled "Mobile Templates" for this blog: check it out on your iPad, Android, iPhone, or mobile device: it looks really cool on my HTC Evo!

    Monday, January 17, 2011

    Run Android tests in a connected device

    Not quite sure as to why it never occurred to me, but it is totally possible and legal to run unit tests inside a real device, connected to your dev box via a USB cable.


    An obvious advantage is that you are now running your tests in a more "realistic" environment; there are no drawbacks that I can think of (unless your device has some weird 'lockdown' imposed by the manufacturer / cell provider); and... that's when you realize just how much faster than an emulator that is.


    So here's the day's top-tip: if you are in a hurry, and have a lot of unit test you want to run, get that USB cable out!

    Saturday, January 15, 2011

    Using the same model classes in Android, GWT and JPA (Part II)

    In a recent post, I've demonstrated how one can use the same domain-specific (Model) classes end-to-end, from the Mobile layer, to the GWT Front-End, up to server-side and Persistence layer (JPA).

    This blog has now been moved to codetrips.com: please read the rest of this post here.