Archive for the ‘Everything Else’ Category

Added UDP Transmitter to DKit to Round Out I/O Package

Wednesday, May 30th, 2012

DKit Laboratory

This morning I wrote a simple, yet effective, UDP transmitter for DKit. The idea is simple - if we have a UDP receiver for datagrams, then it makes sense to have a transmitter of the same. Simple make it a subclass of the sink and we should be ready to go. We can have it share io_service threads like the receivers, but since the transmitters have a slightly different usage on the io_service threads, it's probably a good idea to leave them separate for now.

We can certainly make a simple io_service base class for both the receiver and transmitter and pull these into this base class if we need to, but since the transmitter's need to have a boost::io_service::work defined for them - lest the io_service's run() method return too quickly due to nothing to do, it's different than the receivers, and simple enough to pool on the transmitters, as needed.

The one trick was the virtual template classes problem that I solved previously. I do not want to make the inclusion of the UDP transmitter require that the user know what type to use, so I made a very simple, and very clean subclass that then becomes the basis of the UDP transmitter:

  namespace detail {
  template <class T> class basic_udp_transmitter :
    public sink<T>
  {
    public:
      basic_udp_transmitter() { }
      virtual ~basic_udp_transmitter() { }
 
      /**
       * This is the main receiver method that we need to call out to
       * a concrete method for the type we're using. It's what we have
       * to do to really get a virtual template class working for us.
       */
      virtual bool recv( const T anItem )
      {
        return onMessage(anItem);
      }
 
      /**
       * This method is called when we get a new datagram, and because
       * we are expecting to instantiate this template class with the
       * type 'T' being a <datagram *>, this is the method we're expecting
       * to get hit. It's just that simple.
       */
      virtual bool onMessage( const datagram *dg )
      {
        /**
         * This method will be overridden by the specialization of
         * this template class.
         */
        return true;
      }
  };

and then the main class looks like this:

  class udp_transmitter :
    public detail::basic_udp_transmitter<datagram*>
  {
 
    // …
 
    /********************************************************
     *
     *                Processing Methods
     *
     ********************************************************/
    /**
     * This is the specialized template method that will be called from
     * the generalized recv() method, above, and will, in fact, be the
     * place where we do all the work of sending out the datagram to the
     * UDP multicast channel.
     */
    virtual bool onMessage( const datagram *aDatagram );
 
    // …
 
  };

At this point, it's easy to use the udp_transmitter because I've wired it all up to send the datagrams out via boost ASIO:

  udp_transmitter  xmit(multicast_channel("udp://239.255.1.1:30001"));
  rcvr.addToListeners(&xmit);

The threads are all handled in the same manner as the UDP receiver, so we know they are clean with the reference counting and the clearing of the sockets. It's a nice, clean implementation. You just need to wire it up to a source and it's going to send out those datagrams as they arrive.

Sweet.

It's nice to get this done and really get the next cut of the library done. It's now got receivers and transmitters, and I can build on these as needed or add in more receivers and transmitters (ZeroMQ, etc.) as needed.

Google Chrome dev 21.0.1155.2 is Out

Wednesday, May 30th, 2012

Google Chrome

This morning I noticed that Google Chrome dev 21.0.115.2 was out which marks the next major version number update in a while. It's got a new V8 javascript engine, as well as a few more experimental features enabled by default. It's nice to see it move along, and the number of times that I've been disappointed in the update - primarily due to screen redraw, are getting fewer and farther between. That's a great thing.

Glad to see the progress.

Added Adapter Class to DKit

Tuesday, May 29th, 2012

DKit Laboratory

Today I spent the time to finish up the addition of the adapter class to DKit. The idea is pretty simple: place a source and sink back-to-back and have their template types independent, and there you go! The multiple inheritance virtual template class is a little tricky in getting all these templates working, but I got it - eventually.

The original implementation was designed to simply use the API of the source and sink, but then I ended up getting into trouble with the accessing of protected methods in the source and sink, so I needed to lean a little more heavily on the actual implementations of the source and sink. This works well, too, as we then only have one codebase that we have to maintain - and that's always a good thing.

The implementation is really just a combination of the source and sink, but it affords me the flexibility of making a base class that takes a certain type, and generates a certain type, and with a little template specialization, it all comes together very simply and easily for the user.

I worked up a simple test adapter, and it's pretty clean:

  template <class TIN, class TOUT> class MyAdapter :
    public dkit::adapter<TIN, TOUT>
  {
    public:
      MyAdapter() { }
 
      /**
       * This is the main receiver method that we need to call out to
       * a concrete method for the type we're using. It's what we have
       * to do to really get a virtual template class working for us.
       */
      virtual bool recv( const TIN anItem )
      {
        return dkit::adapter<TIN, TOUT>send(convert(anItem));
      }
 
      /**
       * This method is called when we get a new datagram, and because
       * we are expecting to instantiate this template class with the
       * type 'T' being a <datagram *> this is the method we're expecting
       * to get hit. It's just that simple.
       */
      std::string convert( const datagram *dg ) {
        std::string     out = "<null>";
        if (dg != NULL) {
          std::cout << "converting: " << dg->contents() << std::endl;
          out.assign(dg->what, dg->size);
        }
        return out;
      }
  };

As with the sink, we need to include the recv() method, and then call the specialized method that will do the actual work. In many cases, this specialized method can be a virtual method, making the implementation of the subclasses even simpler. I think it's a pretty solid design, and I'm happy with it.

I'd still like to add a UDP transmitter, and I hope to get to that tomorrow - just to round out the library for completeness.

The News for Facebook Gets Worse

Tuesday, May 29th, 2012

Facebook

Today the news for Facebook gets even worse. Down another 9.62% on the day. It's dropped below $30 now, and it doesn't look good. I'm sure there are people in the next few days that will be saying "Time to buy!", but I find that just wishful thinking on their part.

There have been numerous articles written about the rise of Facebook on the mobile platforms that are all free, but show no adds - which is the lion share of the revenue stream for Facebook. Remove the adds, and the income to support the infrastructure simply isn't there. So they need the adds, but those aren't being valued as highly, or the belief among investors is that they shouldn't be.

More Facebook Sorrow

It's not like I want people to loose money, but this Emperor's New Clothes with Facebook really had to come to an end. It's not the darling of Wall Street - it's an add company, and it's providing a data hosting/sharing service, and while their subscriber numbers are huge, they can't really grow all that much simply because that are that big.

It's time for them to diversify, and quickly. They need to do a Google, and try to get into a few other things that are as used and needed for a different reason. I'm not at all sure what that is, but I can't believe they can continue on this pace for much longer without trying to bolster investor confidence.

Facebook IPO Now a Lawsuit

Wednesday, May 23rd, 2012

Facebook

This morning there's a new story about the Facebook IPO - Zuckerberg, Morgan Stanley are now being sued over the Facebook IPO based on the dismal performance - based (claims the suit) on withheld knowledge of the weak growth forecasts. I was never a fan of the Facebook IPO - but I haven't been a fan of Facebook in general. If anything, I think it's the extreme case of The Emperor's New Clothes - on a nearly global scale.

The vast majority of folks on Facebook are totally unaware that they are what's being sold. That being said, the profitability of Facebook depends on the users clicking on the ads to generate ad revenue for Facebook. Minus that, it's dead. If advertisers see that their ad dollars are being wasted there, they will simply go somewhere else - it's very simple. With the onset of hand-held apps for Facebook, the ads are gone, and therefore, the revenue - but that's just how people want to use it. Free and freely.

Looking at the chart of the first few days of trading for Facebook, it doesn't look anything like what people were expecting - or should I say hoping for…:

Facebook Decline

What you've got is pretty much exactly what Zuckerberg planned - sell the idea of a great IPO, and hope that you'll therefore have one. But business people aren't, as a general rule, complete defuses. They tend to see what's really valued and what's not. At least more often than not. And this is a classic case of The Emperor's New Clothes.

There's nothing to Facebook that the users don't bring to it. Which means the only barrier to entry is pulling those users away from Facebook. I've looked at Google+, and while the first versions weren't all that great, the latest version on my iPhone is much better. It's still the case of trying to sell me, but I don't use it that way. Nor would I think that Google were valued by Google+ alone.

This is one IPO that I wasn't ever interested in, and am glad I'm not working for anyone that's heavily invested in it. It's a smoke-and-mirrors game, and it's not going to tank immediately, there are now too many shareholders that want it to succeed, but it's the beginning of the end for the "darling" of the industry.

But hey… it's just a social networking site. There were others, there will be others. And this will be just a distant memory - like Napster, Netscape, and AOL.

General Template Usage with Pointers

Monday, May 14th, 2012

DKit Laboratory

This evening I finished up adding pools to DKit, and there are a few things that make it so bloody cool I had t write about it. In short, the problem is one that I've had to deal with before: How to make a simple pool of things such that I only create what I need, but don't over create, and can use a manageable set of things from a pool.

Like say I wanted to have a messaging system. I might want to have a bunch of std::string values that are created with a minimum size to make it easy to move things around. Then, all I would need to do is to get one from the pool, clear it out, add in the data, and then when I'm done, return it to the pool. The location in the code that gets from the pool is at a totally different place than the place that recycles these instances, and it's possible that due to threading or queueing, we may need to have several in play all at once. But eventually they will all come back to be recycled.

In the past, I had one class for a std::string pool, and another for datagrams, and so on. Each of these was almost identical to the other, just in how the instance was created. Typically, I'd have some sense of the 'default' size of the container I was creating. I based each off a single type of FIFO queue, so that it would always be a SP/SC pool, etc. This was necessary because I hadn't super classed the FIFO queues as I have in DKit.

Still… this was a lot of copy-n-paste reuse, and it was clear that it wasn't anywhere near as flexible as it could be. So today I decided to try and see what I could get away with if I tried to make a complete template pool class. The challenges were pretty clear:

  • Include the Type of the Queue in the Template - I knew that now that I had the FIFO abstract template class in DKit, it was going to be possible to have the constructor make a queue of the right type, and then just "use it" via the FIFO abstract template class and be able to allow the user to define what access type they wanted for the pool.
  • Include the Max Size of the Pool as a Power of Two - this was in keeping with the queues I'd be creating, and so shouldn't prove to be too hard.
  • Allow Pointers and Non-Pointers to be Pooled - this was the biggest challenge I faced, to be sure. In the pool, I wanted to have two basic methods: next() to get a new one from the pool, and recycle(T) to return it to the pool. The problem is what if the type 'T' is a pointer versus a non-pointer? How do we make sure we can delete a pointer, but simply let a uint64_t fall on the floor and be cleaned up?

Thankfully, I was able to look on Stack Overflow and see this interesting question which lead me to the answer I needed. What it really boiled down to was that I could use the boost::is_pointer(), but that only really lets me know if I need to clean up the contents of the queue in the clear() method. The trick to constructing and destructing was to realize that the templates worked outside the scope of the class definition, and so after the class definition, I added in these functions:

  namespace dkit {
  namespace pool_util {
  /**
   * In order to handle both pointers and non-pointers as data
   * types 'T' in the pool, we need to take advantage of the
   * template methods and make create() and delete() methods
   * for pointers and non-pointers.
   *
   * For create(), it's pretty easy - we allow for nothing to be
   * done for the non-pointer, and a standard 'new' for the pointer.
   * For delete(), it's the same - we delete it and then NULL it
   * out if it's a pointer, if it's not, we do nothing.
   */
  template <typename T> void create( T t ) { }
  template <typename T> void create( T * & t )
  {
    t = new T();
  }
 
  template <typename T> void destroy( T t ) { }
  template <typename T> void destroy( T * & t )
  {
    if (t != NULL) {
      delete t;
      t = NULL;
    }
  }
  }      // end of namespace pool_util
  }      // end of namespace dkit

Then, in the critical next() and recycle() methods, I simply used these functions:

  /**
   * This method is called to pull another item from the pool, or
   * create a new one if nothing is in the pool. This is the classic
   * way of getting the "next" item to work with.
   */
  T next()
  {
    T      n;
    // see if we can pop one off the queue. If not, make one
    if ((mQueue == NULL) || !mQueue->pop(n)) {
      pool_util::create(n);
    }
    // return what we have - new or used
    return n;
  }
 
 
  /**
   * This method is called when the user wants to recycle one of
   * the items to the pool. If the pool is full, then we'll simply
   * delete it. Otherwise, we'll put it back in the pool for use
   * the next time.
   */
  void recycle( T anItem )
  {
    if ((mQueue == NULL) || !mQueue->push(anItem)) {
      pool_util::destroy(anItem);
    }
  }

By using the create(n) and destroy(n) functions, I allow the compiler to see the template functions and pick which one to use. In the case of a pointer for 'T', it chooses the pointer-reference argument, in the case of a non-pointer, it's the pass-by-value argument. This selectivity allows me to partially implement these any time I want in order to make the actual construction and destruction as complicated as I need without requiring it for the simple default constructor and destructor.

Once I had this, the remaining problems weren't too bad at all.

I created an enum for the type of access to use:

  /**
   * We need to have a simple enum for the different "types" of queues that
   * we can use for the pool - all based on the complexity of the access. This
   * is meant to allow the user to have complete flexibility in how to ask for,
   * and recycle items from the pool.
   */
  namespace dkit {
  enum queue_type {
    sp_sc = 0,
    mp_sc,
    sp_mc,
  };
  }       // end of namespace dkit

and then it was pretty simple to make the template and the constructor:

  template <class T, uint8_t N, queue_type Q> class pool
  {
    public:
      pool() :
        mQueue(NULL)
      {
        switch (Q) {
          case sp_sc:
            mQueue = new spsc::CircularFIFO<T, N>();
            break;
          case mp_sc:
            mQueue = new mpsc::CircularFIFO<T, N>();
            break;
          case sp_mc:
            mQueue = new spmc::CircularFIFO<T, N>();
            break;
        }
      }
 
  …
  };

In the end, the code worked wonderfully. I built a test app that made sure the destructor was properly being called when recycle() was being called and the queue was full - check. I also made sure that when the pool was destructed, any remaining elements were properly destructed - if they were pointers.

It was really an amazing little bit of code. This is far more flexible and better than the previous single-purpose pools I've written. Less code is always better.

Added Source and Sink Template Classes to DKit

Friday, May 11th, 2012

DKit Laboratory

Today I wanted to add a little bit more to DKit, so I decided that the next best thing to add were the concepts of a template source and sink. When I built the MessageSource and MessageSink back at PEAK6, I did it in the context of a Message object. That was fine, because that's all we needed, but this time I wanted to make it a little better - no a lot better, so I made the source and sink template classes.

This will allow me to use the pointers like I did before, but it will also make it very easy to use integers, or doubles - or anything. This will be a far better solution to the problem than a fixed class, or pointer to a class.

The only real problem I ran into - if there was indeed any real problems, was the syntax for specifying the template class methods in the implementation file. The header was pretty clear and straight forward, but the implementation was a bit trickier.

Thankfully, I was able to find some examples on the web, but the syntax was pretty bad. I mean really bad. For example, let's say I had the following template class:

  namespace dkit {
  template <class T> class source
  {
    public:
 
      virtual void setName( const std::string & aName );
      virtual const std::string & getName() const;
      virtual bool addToListeners( sink<T> *aSink );
 
  };
  }     // end of namespace dkit

then the implementation file would have to look something like this:

  namespace dkit {
 
  template <class T> void source<T>::setName( const std::string & aName )
  {
    boost::detail::spinlock::scoped_lock  lock(mMutex);
    mName = aName;
  }
 
 
  template <class T> const std::string & source<T>::getName() const
  {
    return mName;
  }
 
 
  template <class T> bool source<T>::addToListeners( sink<T> *aSink )
  {
    bool       added = false;
    // first, make sure there's something to do
    if (aSink != NULL) {
      // next, see if we can add us as a source to him
      if (aSink->addToSources(this)) {
        // finally, make sure we can add him to us
        added = addToSinks(aSink);
      }
    }
    return added;
  }
 
  }     // end of namespace dkit

Now I understand the need to clearly identify the class - hence the template <class T> on the front, but then it seems to really go overboard there. While I'm sure there's a wonderful reason for all this, it seems to have not undergone any simplification over the years. That's probably part of the problem that folks have with C++ - it's complicated looking. And if you don't get it just right, you're not going to even get it to compile.

But for me, it's just what has to be done in order to have template programming. It's a pain, yes, but it's so incredibly worth it.

JP Morgan Loses $2 billion via Hedging

Friday, May 11th, 2012

pirate.jpg

I usually don't spend a lot of time talking about the industry that is the source of my livelihood, but this story is just too good to pass up. Seems that some brilliant trader decided to hedge his positions with exceptionally bad positions. So bad, in fact, that these hedges - not the original positions, but the hedges, have cost the bank $2 billion, and it's estimated that it might cost them another billion before it's all said and done.

What's even more amazing is that JP Morgan has the cash to take the loss and not post a loss for the quarter. Amazing. First, that they believed the hedges were, in fact, hedges, and that they had more than $2 billion to waste.

If they were, indeed hedges, then they were designed to cancel the loss of the original positions. This means that if the hedges lost value, then it should have been the case that the original positions gained value. So they must have picked the most horrific hedging instruments and then held far too much of them to loose that kind of money.

Really. That's almost impressive.

Apple Released Mac OS X 10.7.4 on Software Updates

Wednesday, May 9th, 2012

Software Update

Just saw on Twitter that 10.7.4 was released and includes a few bug fixes that even effect Acorn, my favorite image editing application. I'm not sure now much it'll effect me, as I'm not loading Photoshop images with more than 200 layers, but it's nice to see that it's getting fixed, and all these fixes will be going into 10.8 Mountain Lion this Summer.

I'm glad that it's all coming together today - a few updates, a building of boost, and then I'm starting to feel like the day hasn't been a waste.

Google Chrome dev 20.0.1130.1 is Out

Wednesday, May 9th, 2012

Google Chrome

I just noticed that the Google Chrome team has released a new dev version: 20.0.1130.1, and the release notes say that it's focusing on a new version of the V8 javascript engine (3.10.8.4), and a raft of stability fixes. Glad that they are still working on things, but it's been a while since I've seen a really new feature or capability released that even remotely impacts me. Still… it's to be expected, really. The browser has become stable. There's HTML5, and it's widely supported in WebKit, and that's in Chrome, Safari, and many others. It's just not that dynamic a platform any more. And that is good news. Stable platforms are nice to write for.