Friday, November 26, 2010

Factory with registerable and configurable units..

One of the most common patterns used in software a factory. The ideal factory has sub units that can register with the main factory using one or more keywords.

The holy grail implementation is the self-registering factory, where the mere definition of the class causes it to register with the Factory. This is not really not really possible in C++ due to the limited RTT typing and introspection of the language. However you can do some 1 liner tricks to get the item to install at startup, such as static/local variables, or an instance function.

Below is a Factory that utilizes its registration to store the keyword, Type and some construction parameters for a factory. Thus allowing repeated of the same type with customized default parameters.

A brief class overview is
Class/TypeDescription
KeyThe description/tag/id for the factory
RegItemBaseThe Factory Registration generic entry
BaseThe Factory output class
RegFactoryThe Factory
RegItemAn item to register with the factory, without any parameters
RegItemParamAn item to register with the factory, without a single parameter
AThe First demo class
BThe Second demo class

#include <iostream>
#include <map>

using namespace std;

/*****************************************************
 *          Factory with registering methods
 *****************************************************/

typedef string Key;

class Base;

class RegItemBase
{
public:
    RegItemBase(Key _key) :
        key(_key)
    {}

    virtual Base* construct()   const = 0;
    virtual void      print()   const = 0;
    virtual const Key keyword() const { return key; }

private:
    Key key;
};
typedef map<Key,RegItemBase*> KeyRegItemMap;

class Base
{
public:
    virtual const RegItemBase* getReg() const = 0;
    virtual const Key keyword() const { return getReg()->keyword(); }
    virtual void      print()   const { cout << keyword() << endl; }
    virtual void      bark()    const { cout << "...." << endl; }
};


class RegFactory
{
public:
    static RegFactory* getInstance() 
    {
        static RegFactory* instance = new RegFactory();
        return instance;
    }

    void add(RegItemBase* item) 
    {
        items[item->keyword()] = item;
    }
    
    Base* construct(Key key) 
    {
        KeyRegItemMap::const_iterator bit = items.find(key);
        if(bit != items.end())
            return bit->second->construct();
        return NULL;
    }
        
    void listAll() 
    {
        cout << "Registered items:"  << endl;

        KeyRegItemMap::const_iterator bit;
        for(bit = items.begin();
            bit != items.end();
            bit++)
        {
            cout << " " << bit->second->keyword() << endl;
        }

        cout << "Registered items DONE"  << endl;
    }

protected:
    RegFactory() {}

private:        
    KeyRegItemMap items;
};


template <class TempType>
class RegItem : public RegItemBase
{
public:
    typedef TempType Type;

    RegItem(const Key _key) :
        RegItemBase(_key)
    {
        cout << "Registering key: " << _key << endl;
        RegFactory::getInstance()->add(this);
    }

    virtual Base* construct()   const { return new Type(); }
    virtual void print()        const { cout << keyword() << endl; }
};

template <class TempType>
class RegItemParam : public RegItemBase
{
public:
    typedef TempType Type;

    RegItemParam(const Key _key, string _param) :
        RegItemBase(_key),
        param(_param)
    {
        cout << "Registering key: " << _key << endl;
        RegFactory::getInstance()->add(this);
    }

    virtual Base* construct()   const { return new Type(param); }
    virtual void print()        const { cout << keyword() << endl; }
private:
    string param;
};

/*****************************************************
 *             Specific Classes to register
 *****************************************************/

class A : public Base
{
public:
    static RegItemBase* reg()
    {
        static RegItemBase* regItem = (RegItemBase*)new RegItem<A>("A");
        return regItem;
    }
    virtual RegItemBase* getReg() const { return A::reg(); }

    virtual void      bark()    const { cout << "ruff" << endl; }
protected:
    friend class RegItem<A>;
    A() {}
};

class B: public Base
{
public:
    static RegItemBase* reg()
    {
        static RegItemBase* regItem  = (RegItemBase*)new RegItemParam<B>("B", "red");
        static RegItemBase* regItem2 = (RegItemBase*)new RegItemParam<B>("C", "green");
        return regItem;
    }
    virtual RegItemBase* getReg() const { return B::reg(); }

    virtual void      bark()    const { cout << "woof " << param << endl; }
protected:
    friend class RegItemParam<B>;
    B(string _param) : param(_param) {}

    string param;
};

int main()
{
    //setup regs...
    A::reg();
    B::reg();

    //list types..
    RegFactory::getInstance()->listAll();

    Base* a = RegFactory::getInstance()->construct("A");
    a->print();
    a->bark();

    Base* b = RegFactory::getInstance()->construct("B");
    b->print();
    b->bark();

    Base* c = RegFactory::getInstance()->construct("C");
    c->print();
    c->bark();
}

http://accu.org/index.php/journals/597

Saturday, November 13, 2010

Adding a syntax higher to your blog

Recently went through the effort of adding syntax highlighting to this blog. Its a worth while and somewhat easy process.. There can be a bit of leg work to up date existing posts but its worth the effort.

  1. Copy the below code;

    <!--SYNTAX HIGHLIGHTER BEGINS-->
    <link href='http://alexgorbatchev.com/pub/sh/current/styles/shCore.css' rel='stylesheet' type='text/css'/>
    <link href='http://alexgorbatchev.com/pub/sh/current/styles/shThemeRDark.css' rel='stylesheet' type='text/css'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushBash.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCpp.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCSharp.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCss.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJava.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJScript.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPhp.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPython.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushRuby.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushSql.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushVb.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushXml.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPerl.js' type='text/javascript'/>
    <script language='javascript'>
    SyntaxHighlighter.brushes.Clojure = function()
    {
            // Contributed by Travis Whitton
    
            var funcs = &#39;:arglists :doc :file :line :macro :name :ns :private :tag :test new add-hook alias alter and apply assert class cond conj count def defmacro defn defun defstruct deref do doall dorun doseq dosync eval filter finally find first fn gen-class gensym if import inc keys let list loop map ns or print println quote rand recur reduce ref repeat require rest send seq set setq sort str struct sync take test throw trampoline try type use var vec when while&#39;;
    
            this.regexList = [
                    { regex: new RegExp(&#39;;[^\]]+$&#39;, &#39;gm&#39;),                           css: &#39;comments&#39; },
      { regex: SyntaxHighlighter.regexLib.multiLineDoubleQuotedString, css: &#39;string&#39; },
                    { regex: /\[|\]/g,                                               css: &#39;keyword&#39; },
      { regex: /&#39;[a-z][A-Za-z0-9_]*/g,                                 css: &#39;color1&#39; }, // symbols
      { regex: /:[a-z][A-Za-z0-9_]*/g,                                 css: &#39;color2&#39; }, // keywords
      { regex: new RegExp(this.getKeywords(funcs), &#39;gmi&#39;),             css: &#39;functions&#39; }
                ];
     
     this.forHtmlScript(SyntaxHighlighter.regexLib.aspScriptTags);
    }
    
    SyntaxHighlighter.brushes.Clojure.prototype     = new SyntaxHighlighter.Highlighter(); 
    SyntaxHighlighter.brushes.Clojure.aliases       = [&#39;clojure&#39;, &#39;Clojure&#39;, &#39;clj&#39;, &#39;lisp&#39;];
    </script>
    <script language='javascript'>
    SyntaxHighlighter.config.bloggerMode = true;
    SyntaxHighlighter.config.clipboardSwf = &#39;http://alexgorbatchev.com/pub/sh/current/scripts/clipboard.swf&#39;;
    SyntaxHighlighter.config.strings.expandSource = &#39;show source&#39;;
    SyntaxHighlighter.config.strings.viewSource = &#39;view source&#39;;
    SyntaxHighlighter.all();
    </script>
    <!--SYNTAX HIGHLIGHTER ENDS-->
    
  2. Note that i have a custom hightlighter in this set for lisp (emacs configs etc)
  3. Go to Blogger Dashboard > Layout > Edit HTML.
  4. Press CTRL+F to find the code </html>.
  5. Add the code to the location before the final </b:section-contents>. This depends highly on what blogger template you have, so you may need to experiment with it a bit. You want to add the syntax highlighter to the end of the page because if the 3rd party site providing javascript is down or under heavy load your blog wont load its content.
  6. You can alter the Color Theme from "shThemeRDark.css" with different ones as explained here
    http://alexgorbatchev.com/SyntaxHighlighter/manual/themes/

  7. Then to highlight a section of code add the following around it in the blogger edit/new posts screen.
    <pre class="brush:cpp">
    //code here
    </pre>
    
    The item after the "brush:" is altered to match your code syntax. The possibles are listed here; http://alexgorbatchev.com/SyntaxHighlighter/manual/brushes/. Of course you need to check that you have installed the brush to get the highlight working.


  8. Other Refs;
http://www.cyberack.com/2007/07/adding-syntax-highlighter-to-blogger.html

sygnery - ubunutu mouse/keyboard sharing with a Mac-- bootup

Find, download and install the sygnery client(mAC) and server for the respective machine

Note that the machine names will need to be replace with whatever yours are mine are:
mac-mini.local
ubuntu-desktop

################### CLIENT (MAC OSX) #####################
For the mac client. (IE not using the mac mouse or keyboard)
mkdir ~/LoginItems
cat > ~/LoginItems/start_synergy.command 
/Applications/synergy/synergyc -f 

Then in Settings -> Accounts -> select the user -> login items
Add the .command file as a terminal shell script.


################### SERVER (UBUNTU) #####################

For the ubutu server. (IE not using the ubuntus mouse or keyboard, on a remote)

vi .synergy.conf

Add the lines
section: screens
ubuntu-desktop:
mac-mini.local:
super = alt
alt = super
end
section: links
ubuntu-desktop:
right = mac-mini.local
mac-mini.local:
left = ubuntu-desktop
end

Assuming your a bash user
vi .bashrc

Add the lines
sysergys_exec=`ps -A | grep synergys`
if [ "$sysergys_exec" = "" ]
then
synergys 
fi

Then restart(only really need to logout/login) and see what happens.

You could run the server globally from your xwindows config or even from start up but i prefer to have it in my bash where i can get at it and modify it easier.

switching users with sudo

sudo -u otheruser /bin/bash

Monday, November 1, 2010

Perl file search, loc, action

Find a file with the text and take the action on it. (in this case do a clearcase checkout)

find ./ | xargs perl -ne 'print "cleartool co -nc $ARGV\n" if m/endl/' | uniq | sh

Perl sed replacement

Gezz.. who let the squirrels into the server room.. there is nutty #$%& everywhere.. so now I have no sed go figure..

ls | xargs perl -ne 'print "$ARGV:$. $_" if m/endl/'

endl vs "\n"

Someone recently asked my why I used endl lines in place of "\n" must say I forgot that they are different. The key point is; Endl Forces a flush of the data stream as well as adding a new line. Where as "\n" is just a "raw" end of line.

A raw "\n" is used when you just need a new line and you dont care either way. IE User logs, data file writing, etc.

The idea usage of endl line is that the buffer is cleared in a timely fashion out the the user or stream. This is needed when the buffering may cause the unacceptable drag out of the final piece of data. IE networks, user prompts, etc

The other point to remember is that endl isn't always compatible with other libraries. For example boost lamba functions and Qt streams dont always react well to endl.

Of course unless your dumping thousands of lines here u shouldn't really have anywaycare.