Stop Watch and Time Out Classes

I have a passing interest in stop watch and time out type classes. Keeping track of elapsed time, remaining time. They are very basic classes, but I find them interesting.

GetTimeMS function

The stop watch and timer classes use this function to get the system time, we actually return the system time minus the application start time to get a time relative to the application start time, starting at 0. This is not necessary, return the system time is fine, returning the time the application is running is usually just easier to think about than the time since 1970, which is kind of arbitrary.
This function uses milliseconds, if this is not enough, we can easily switch to nanoseconds.

typedef uint64_t durationms_t;
 
// Get the time since epoch in milliseconds
durationms_t GetTimeMS()
{
  static const std::chrono::system_clock::time_point start = std::chrono::system_clock::now();
 
  const std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
  return std::chrono::duration_cast<std::chrono::milliseconds>(now - start).count();
}

Stop watch class

Provides start, stop, reset and we can get the total duration.

class cStopWatch
{
public:
  cStopWatch();
 
  void Start();
  void Stop();
  void Reset();
 
  durationms_t GetTotalDurationMS() const;
 
private:
  bool running;
  durationms_t started;
  durationms_t totalDuration;
};
 
cStopWatch::cStopWatch() :
  running(false),
  started(0),
  totalDuration(0)
{
}
 
void cStopWatch::Start()
{
  assert(!running);
 
  // Started our stop watch
  started = GetTimeMS();
 
  running = true;
}
 
void cStopWatch::Stop()
{
  assert(running);
 
  // Get the time now
  const durationms_t now = GetTimeMS();
 
  // Add the duration for this period
  totalDuration += now - started;
 
  // Reset our start time
  started = 0;
 
  running = false;
}
 
void cStopWatch::Reset()
{
  started = 0;
  totalDuration = 0;
 
  running = false;
}
 
durationms_t cStopWatch::GetTotalDurationMS() const
{
  if (running) {
    // Get the time now
    const durationms_t now = GetTimeMS();
 
    // Return the previous duration plus the duration of the current period
    return totalDuration + (now - started);
  }
 
  return totalDuration;
}

Example usage

cStopWatch stopWatch;
 
// Start the stop watch
stopWatch.Start();
 
// Sleep for 1 second
const uint64_t timeout_ms = 1000;
::usleep(1000 * timeout_ms);
 
// Stop the stop watch
stopWatch.Stop();
 
// We have now waited for at least 1 second
std::cout<<"Stop watch time: "<<stopWatch.GetTotalDurationMS()<<" ms"<<std::endl;

Time out class

Allows us to get the time remaining, check if the time out has expired and reset the time out.

class cTimeOut {
public:
  explicit cTimeOut(durationms_t timeout);
 
  void Reset();
 
  bool IsExpired() const;
 
  durationms_t GetRemainingMS() const;
 
private:
  const durationms_t timeout;
  durationms_t startTime;
};
 
cTimeOut::cTimeOut(durationms_t _timeout) :
  timeout(_timeout),
  startTime(GetTimeMS())
{
}
 
void cTimeOut::Reset()
{
  startTime = GetTimeMS();
}
 
bool cTimeOut::IsExpired() const
{
  return ((GetTimeMS() - startTime) > timeout);
}
 
durationms_t cTimeOut::GetRemainingMS() const
{
  // Get the total time this timeout uhas been running for so far
  const int64_t duration = int64_t(GetTimeMS()) - int64_t(startTime);
 
  // Calculate the remaining time
  const int64_t remaining = (int64_t(timeout) - duration);
 
  // Return the remaining time if there is any left
  return (remaining >= 0) ? remaining : 0;
}

Example usage

// Create a 5 second time out
cTimeOut timeout(5000);
 
// Wait until the time out is expired
while (!timeout.IsExpired()) {
  std::cout<<"Waiting..."<<std::endl;
 
  // Sleep for 1 second
  const uint64_t timeout_ms = 1000;
  ::usleep(1000 * timeout_ms);
}
 
std::cout<<"Time out reached"<<std::endl;

Colour Picker Added Hex and Float Conversions

Colour picker hex and float entry.
Colour picker hex and float entry.

The colour pickers I see never have conversions from RGB uint8_t 255, 255, 255 to RGB float (1.0f, 1.0f, 1.0f), so I added it to mine.
HSL, HSV and YUV are also shown.
There is one bug when typing in a text colour if no single RGB component dominates then the colour palette look up fails, picking full white.
It’s in JavaScript, so as usual I am surprised by how quickly and relatively easy this was to implement. The biggest issues I had were not knowing how JavaScript converts strings to and from numbers.

Try It
Source

Some Simple Regexes for Finding If Statements

I know almost nothing about regexes, these are just some useful ones I created for checking code style, if statements specifically.

Find single line if statements (Useful when your coding style requires adding curly braces to everything):

/^ *if \(.+\).*(;)/igm

regex101

Find multiple line if statements (Useful when your coding style favours less lines):

/^ *if \(.+\).*({)/igm

regex101

Regex101 is really impressive.  You can paste a regex and check it against some test inputs.  The best part is the description of what each symbol in your regex does and even what some of the combined parts do, such as various brackets around groups of expressions.

openglmm_shaders Test 20150817

Here is a video demo of my OpenGL 3.3 library libopenglmm.
Source

YouTube Video

Materials:
Lambert shading (Mirror’s Edge style)
Fog
Cube mapping
Multitexturing
Normal mapping
Car paint (Slighty broken, I think a texture look up is incorrect)
Glass mixed with dirty metal texture (Similar to an old rusty/broken mirror)
Cel shading
Smoke particle system with lambert lighting with 4 normals that very roughly approximate a sphere (I think something is wrong with the depth texture look up)

Post render effects:
Sepia
Teal and orange
Noir
Matrix
HDR (It is cheesy and over done, but you get the idea, it would normally be a lot more tame, either brought back or blending less of the HDR textures in at the end)
Colour blind simulation (3 modes are possible, only one is shown)

Colour Picker Released

Colour Picker in action

I created a colour picker in JavaScript, then I created 3 variations that simulate the common colour blindnesses. They are all linked so that when you select a colour in one it picks the “same” colour in the others. I mainly just created it out of interest. I realise there are similar colour blind simulator tools, but I hadn’t seen any that used linked colour pickers like this.

I don’t normally use JavaScript, but I had fun doing this. The syntax is easy to read and relatively sane. The rapid development is great and the HTML5 features such as canvas are easy to use and quite powerful.

Try it
Source

Diesel Photo Manager 0.1 Released

I couldn’t find a photo browser for Linux that also imported my photos in the folder format I wanted so I created my own.

This is the first release and it has these features:

  • Simple interface
  • Thumbnail grid mode
  • Single photo mode
  • Import and sort photos into folders based on the date
  • Convert files to dng
  • Show the background thread progress on the statusbar
  • Check for updates via version.xml
  • Default to dark theme (Can be overridden with the –light command line parameter)

Still to come:

  • Fixes to the single photo viewing mode
  • Popup notifications when a new track is played
  • Work out what I want to do with the photo browser

Thumbnail browsing mode
Thumbnail browsing mode

Download
Source

Medusa Music Player 0.9 Released

I’ve release a new version of Medusa music player with these features:

  • Simple interface
  • Last.fm support
  • Date added and a full file path column
  • Drag and drop from the file manager
  • Moving files to the trash folder
  • Move files to a particular folder and remember the last 5 folders
  • Extra columns
  • Show the background thread progress on the statusbar
  • Import playlist from Rhythmbox and Banshee
  • Autoplay at last track at startup
  • Web server for controlling playback, volume and deleting tracks remotely
  • Check for updates via version.xml
  • Popup notifications when a new track is played

New:

  • Various bug fixes
  • Web server bug fixes
  • Default to dark theme (Can be overridden with the –light command line parameter)

Still to come:

  • Easy tag editing for multiple files at once

Dark Theme
Dark theme

Download
Source

Medusa Music Player 0.8 Released

I’ve release a new version of Medusa music player with these features:

  • Simple interface
  • Last.fm support
  • Date added and a full file path column
  • Drag and drop from the file manager
  • Moving files to the trash folder
  • Move files to a particular folder and remember the last 5 folders
  • Extra columns
  • Show the background thread progress on the statusbar
  • Import playlist from Rhythmbox and Banshee
  • Autoplay at last track at startup

New:

  • Web server for controlling playback, volume and deleting tracks remotely
  • Check for updates via version.xml
  • Popup notifications when a new track is played

Still to come:

  • Easy tag editing for multiple files at once

Medusa Main Window
Medusa Main Window
Download
Source

Medusa Music Player 0.7 Released

I’ve release a new version of Medusa music player with these features:

  • Simple interface
  • Last.fm support
  • Date added and a full file path column
  • Drag and drop from the file manager
  • Auto play last track at startup
  • Moving files to the trash folder
  • Move files to a particular folder and remember the last 5 folders

New:

  • Extra columns
  • Show the background thread progress on the statusbar
  • Import playlist from Rhythmbox and Banshee
  • Add autoplay at last track at startup

Still to come:

  • Easy tag editing for multiple files at once

Medusa Main Window
Download for Linux
Source

Medusa Music Player 0.6 Released

I’ve release a new version of Medusa music player with these features:

  • Simple interface
  • Last.fm support
  • Date added and a full file path column

New:

  • Drag and drop from the file manager
  • Auto play last track at startup
  • Moving files to the trash folder
  • Move files to a particular folder and remember the last 5 folders

Still to come:

  • Easy tag editing for multiple files at once

Medusa Main Window
Download for Linux
Source

Java Gotchas

Java

  • Everything is a pointer that initially points to null. Every non-POD type must be newed (I forget this one a lot)
  • The POD types (int, float, enum, etc.) behave just like their C++ counter parts.
    The boxed versions (Integer, Float) and String in Java are more like a pointer to the POD value.
    For example:

    String a = "chris";
    String b = "chris";
    if (a == b) System.out.println("The strings are the same");

    This test will always fail because operator== for pointers (Instances of anything derived from java.lang.Object) will test if the pointers point to the same memory.
    To compare boxed types:

    if (a.equals(b)) System.out.println("The strings are the same");
  • Strings are immutable in Java, this doesn’t work as expected:
    String a = "a";
    a.replace('a', 'b');
    System.out.print(a); // Prints "a" instead of "b"

    A copy must be made:

    String a = "a";
    String b = a.replace('a', 'b');
    System.out.print(a); // Prints "b"

    String toUpperCase and toLowerCase have the same problem.

  • Java finalize() is not a C++ destructor.  It is not guaranteed to be called.  If a finalize() function is called it is up to the child class to call super.finalize().
  • If you specify no access modifier in C++ the default behaviour is private to the class, in Java it is private to the package. If you are bitten by this bug it kind of serves you right because you should always specify an access modifier anyway, but it may bite you when porting old code from C++.
  • There is no way to choose what lives on the stack and what lives on the heap. It doesn’t really matter most of the time, but it would be nice to have the option.
  • There is no passing by reference, everything is passes as a pointer.
  • There are no function pointers, anonymous interfaces are probably the closest thing to it.
  • Copy vs Reference Confusion
    Car a = new Car();
    a.SetColour("red");
    Car b = a; // Takes a reference to a, does not create a copy
    b.SetColour("blue");
    System.out.print(a.GetColour()); // Prints "blue"
  • Java final is not the same as C++ const
    class PaintShop {
      public void PaintCarBlue(final Car car) {
        car.SetColour("blue"); // Changes the colour of the original car
      }
    }
     
    PaintShop paintShop = new PaintShop();
    Car a = new Car();
    a.SetColour("red");
    paintShop.PaintCarBlue(a);
    System.out.print(a.GetColour()); // Prints "blue"

Medusa Music Player 0.5 Released

I’ve been working on a music player for Linux. What I really wanted was foobar2000 for Linux but nothing on Linux is quite like it. There are lot of iTunes clones (Amarok, Banshee, Songbird, Rhythmbox, etc) but they are all too complicated or make copies of your music or show you lyrics and Wikipedia articles and include a web browser. I just want a simple music player. I can list the features I want one hand (I’ve only implemented the struck through items so far):

  • Simple interface (Most are not simple but can be configured to be simple)
  • Last.fm support (They all do this)
  • Date added and a full file path column (You would be surprised at just how many music players do not have these columns but they are so useful for sorting by)
  • Moving files to the trash folder (Most can do this)
  • Easy tag editing for multiple files at once (Most are ok at this)
  • Move files to a particular folder and remember the last 5 folders (Useful for remembering which songs I like by putting them in a “Collection” folder. I haven’t seen any other players do this)

This is a very early version, I’ve only implemented 3 out of 6 of the proposed features. By the time I release a 1.0 version I hope to have all of these features implemented.
Medusa Main Window
Download
Source

Debugging 101

Tips to help you find bugs.

Turn the warning level up and turn on warnings as errors
I know, it can be a pain, but it works. It helps you produce more rhobust, forward compatible, portable code that is syntactically correct on more compilers.
Use assert …
Assert will help you find errors before you even knew there was a problem. It is 100x better if your application tells you exactly where problems are and breaks into the debugger than for your application to crash for the customer. It goes hand in hand with compile time type safety, compiler warnings and static_assert.
… and use if () return
Think of assert as flagging the problem for you to fix and if () return as guarding the application from crashing for the customer.
Print to your errors/trace file
It can be easier to read what the application did rather than stepping through it, in some cases it is not possible to step through the code at all; full screen games, embedded devices and drivers for example. Print out variables, function entrance/exit and “I am here” lines.
Simplify
Comment out or remove as much code as possible. Slowly remove lines until you find the offending line. Try different ways of doing the same thing. Read your errors/trace file. If I had a dollar for every time a coworker tells me there is a bug in the library/standard library/compiler/Operating System and it is actually an error in their code and they have ignored a printed error, I would buy a Ferrari, and then I would buy them a pair of spectacles and I would say, “Use these to read these”, and point at the error message.
Write data to files and validate your files
For example XML, HTML, JSON, RSS, KML, PNG, WAV and MP3, can all be written to files and run through third party validation software. You can even setup a unit test to write these to a file and run the validator for you.
Use your debugger
Put break points on suspect lines, step through functions, find out the value of variables, look at what each thread is doing, look at the call stack.
Read the documentation for the library you are using
You may be using a library incorrectly, it may have conditions or prerequisites you didn’t know about. If it is too complex wrap it into something easier to digest. If its usage is error prone wrap it into something simpler and type safe, that only uses what you need. An optimising compiler will factor out your wrapper and it will have no run time impact.
Use STL
It is there for a reason. Millions of developers have used it for almost two decades, hundreds of thousands of eyes have pored over the source code to it. Chances are that it is more capable, less bug ridden and more portable than your hodge podge collection of classes. A large percentage of bugs I have seen are in classes that could be replaced by the STL. Plus developers will “just know” what your code does because they already have experience with STL. Just use it.

Pimp My Code Part 2

Xhibit

char szPassword[255];
GenerateRandomPassword(szPassword, 8);
char szText[255];
sprintf(szText, "User: %s, ID: %d, Password: %s", szUser, int(userid++), szPassword);

Don’t increment and use a variable on the same line. We know, you’re very tricky, you saved a line. You also made sure that beginners to C++ don’t know what the result will be. Keep it simple stupid. Create the simplest most readable code possible, it makes skimming over code and debugging code much easier. Fixed length arrays are very prone to buffer overruns, in this example szPassword is probably only 8 characters long after calling GenerateRandomPassword, but szUser could be any length and could definitely overrun 255 characters. The best way to mitigate this problem is to use a real string class such as std::string. We can also avoid using sprintf by using a type safe string writing class, std::ostringstream. Code using std::ostringstream is also slightly more human readable.

userid++;
const std::string sPassword = GenerateRandomPassword(8);
std::ostringstream oText;
oText<<"User: "<<sUser<<", ID: "<<userid<<", Password: "<<sPassword;
std::string sText = oText.str();

There, type safe, buffer overflow safe, future proof and slightly more readable, what’s not to like?

Pimp My Code Part 1 Redux

Xhibit

Not exactly a redux, but very similar to last time:

bIsNotEmpty = false;
if (vNests.GetSize() != 0) {
  if (vNests[0]->vEggs.GetSize() != 0) bIsNotEmpty = true;
}

First of all we don’t actually care about the size, we just care that we have (Or don’t have) a nest with eggs in it. Depending on the container GetSize may or may not be a variable look up. IsEmpty is always a variable lookup:

bIsNotEmpty = false;
if (!vNests.IsEmpty()) {
  if (!vNests[0]->vEggs.IsEmpty()) bIsNotEmpty = true;
}

We can combine this into a single line:

bIsNotEmpty = (!vNests.IsEmpty() && !vNests[0]->vEggs.IsEmpty());

I would use more descriptive variable naming change my logic to use bIsEmpty/!bIsEmpty. Using bIsNot variables is often confusing and leads to harder to read code:

bIsNestWithEggs = (!vNests.IsEmpty() && !vNests[0]->vEggs.IsEmpty());
bIsEmpty = !bIsNestWithEggs;
// Use bIsEmpty and !bIsEmpty from now on

Pimp My Code Part 1

Xhibit

inline bool IsSpecial(const char* szValue)
{
 // Returns true if this is a special value
 if (stricmp(szValue, "MySpecialValue") == 0) {
   return true;
 }
 
 return false;
}

I see this sort of thing all the time. For boolean functions that call boolean functions the if and return statements are usually superflous, we can use the return value of (stricmp(szValue, “MySpecialValue”) == 0) itself:

// Returns true if this is a special value
inline bool IsSpecial(const char* szValue)
{
 return (stricmp(szValue, "MySpecialValue") == 0);
}

If it were up to me I would also use a string class and keep as much of the code as possible in the string “realm” (This makes the code a lot simpler and easier to read):

// Returns true if this is a special value
inline bool IsSpecial(const string& sValue)
{
 return (sValue == "MySpecialValue");
}

Converting Pentax PEF Files to PNG

Ufraw is a fantastic utility to convert raw camera formats. You can install it via (And you may as well get the plugin for gimp while you are at it):

sudo yum install ufraw ufraw-gimp
OR
sudo apt-get install ufraw gimp-ufraw

There is a great tutorial on using ufraw from a bash script here, my only recommendation is converting to PNG but it is entirely up to personal preference.

PNG version:
pef2png.sh

#!/bin/bash
 
if [ ! -d ./processed_images ]; then mkdir ./processed_images; fi;
 
# processes raw files
for f in *.pef;
do
  echo "Processing $f"
  ufraw-batch \
    --wb=camera \
    --exposure=auto \
    --out-type=png \
    --compression=96 \
    --out-path=./processed_images \
    $f
done
 
cd ./processed_images
 
# change the image names
for i in *.png;
do
  mv "$i" "${i/.png}"_r.png;
done
for i in *.png;
do
  mv "$i" "${i/imgp/_igp}";
done

Usage:

# Convert all pef files in the current directory to png
./pef2png.sh

Committing in the Morning

"I love the smell of napalm in the morning.  It smells like, victory."
“I love the smell of napalm in the morning. It smells like, victory.”

I love the smell of commiting in the morning. It smells like victory. My current strategy is to commit throughout the day until about 3pm. After that I will only commit code that I need to do a release that evening. Otherwise it can wait until the next day. This has a few advantages:

  • I have a chance to think about it in the evening or when I am trying to get to sleep. I might think of a better solution or a way to tidy up my current solution.
  • When I commit it I have a clear mind, if the code I wrote last night is hideous I am much more likely to fix it or not commit it at all.
  • After committing I am present to clean up the repercussions. Many times I have committed just before leaving and co-workers have had to revert or fix my commit. This just wastes time for them, I know the reasoning for my changes, other possible solutions and most importantly I know how the code works. If someone else gets a compile error or run time bug it might not be in an area they are familiar with. They will have to read through the code and work out what it does, what the problem is and how to fix it.

Eclipse

Last time I tried Eclipse (10 years ago?!?) it was incredibly slow. JVMs and Eclipse have both improved remarkably in that time, and Eclipse is now just as fast as KDevelop. There are many nice features that I haven’t seen in other IDEs yet such as a warnings and errors panel that compiles your project in the background. The special feature here is that for every warning and error, Eclipse will offer a few possible solutions to solve it, for example “import java.util.io.File is never used” will offer a few solutions, “Remove unused import”, “Organise imports” and “Add @SuppressWarnings ‘unused'”.

Helpful warnings about unused import
Helpful warnings about unused import

Clicking on “Remove unused import” will automatically remove the line from the code.

Possible solutions, selecting one will make it happen.  I'm not sure what is up with the colours on the example being inverted, perhaps so you don't confuse it with your application's code?
Possible solutions, selecting one will make it happen. I'm not sure what is up with the colours on the example being inverted, perhaps so you don't confuse it with your application's code?
  • There is also automatic adding of imports for the classes used in this file, extracting public classes to new files, creating new packages/classes/methods/variables/enums, add cast to make classes convertible, change type of object to match, rename a similarly named class/method/variable/enum to match this reference to it, change this reference to a similarly named class/method/variable/enum, and what seems like many, many more.
  • There is a way to change how many spaces wide a tab is, but there is no way to insert spaces instead of tabs (I’m sure there is a way to do this but I couldn’t find it).
  • The auto completion feature works as well as modern versions of Visual Studio which is something I have been sorely missing in KDevelop.  Good auto completion is quite rare. Admittedly the C++ case is more complex.  Includes, defines and ifdef/ifndef, mean that a state machine and parsing of all previous code is required to get an accurate auto completion list. Early versions of Visual Studio for example got this very wrong.
  • When it is working, warnings and errors as you type is very handy.
  • Debugging is a bit clunkier compared to KDevelop and Visual Studio (But at least it works which is more than I can say for debugging C++ applications in Xcode (Perhaps Objective C debugging actually works but no one at Apple cares about Carbon any more?)).
  • Various for and while loops can be auto completed using arrays, arrays with a temporary variable, collections and iterators.
  • The create new variable/function/class/file wizard not only works but is actually useful.
  • Refactoring is phenomenal, for example “Extract method” will find similar code throughout the whole class to extract, not just the current selection in one function.

Java

I’ve been getting back into Java in my spare time recently, as I think about possibly making a few Android games. These are some notes about the differences between Java and C++.

  • In Java (almost) everything is an object. Strings, Floats and Ints are first class types.
  • In C++ we usually don’t have to stress too much about performance. We can usually afford to do extra processing, create and pass around as many temporaries as we like, use extra ram and hold onto large amounts of ram. Java dies if you use too many temporaries. Performance in Java is highly reliant on the algorithms used.
  • Java benefits from lazy initialisation, not doing anything you don’t need to until you need to.
  • Caching previous results (But not holding onto excessive amounts of ram).
  • Reducing number of temporaries by using classes such as StringBuilder.
  • Java is fun to use. Like a strict C++. Strict in a good way. It is how C++ should have been created. Unfortunately the C++ standards committee decided that backwards compatability was a higher priority than creating awesomeness.
  • The built in libraries are pretty good. I can still write algorithms quicker in C++ but there is a lot more extra functionality in the standard Java libraries such as regular expressions, file system, networking, threads, gui and sql. This is changing slightly with C++0x, but it still lacks basic things such as XML parsing, sql and anything related to gui.
  • Each file can only contain 1 public class. This enforces good structure on your API, “what is the public interface going to be?”, where in C++ a lot of APIs just throw all classes in the header and allow the user to do whatever they want.
  • Using classes from other files is less broken. The lack of including is a good thing although packages and import are basically the same as namespaces and include/using.
  • Being forced to catch exceptions is great, the compiler makes sure that you are doing something with the exceptions later. If you throw or rethrow an exception you then have to mark your function as “throws ” so that the exception and catching the exception propogates up the call stack. The best part about this is that the compiler then knows exactly where an exception should be handled and produces an error if you haven’t handled it or rethrown it.
  • I miss const. There is final but it isn’t quite the same.
  • I miss for example operator overriding. Some built in classes such as String, Array, Vector, etc. could definitely benefit from it. buffer[0] is easier for me to write and understand at first glance than buffer.get(0).  Geometric vector and matrix classes could definitely benefit from operator overloading too for example a = b + c can be understood instantly, a.Add(b, c) is a bit awkward and I have to think about it, “a is being modified, right, b and c are left unmodified, right?”.
  • I miss complex macros and ifdef/ifndef. These can be very helpful, for example using one class on one platform and another class on the other or sharing all the code in a class except for a few lines that are different. Apparently the JVM should be good enough that you can branch on the platform and use oop to change functionality and not lose too much performance. I’m not sure what the replacement is though for a part of your application that just doesn’t compile on other platforms because it uses a platform specific API.