Saturday, August 20, 2022

Simple example of using the Provider API in Flutter

This is a clean, simple example of how to use the Provider API in your flutter app to do state management. The basic functionality is akin to redux, if you are from a React background. 


The key aspects of using this are as follows:

  1.  KeepYour provider is a Dart class which has all the shared state as required by your application. For example, if you are implementing a shopping application, this class may hols a list of inventory items as well as the the cart data (items ordered, total value, etc.). 
  2. This class should also implement all the business logic, as required by the application. For instance, it should add up all the total cost of items on order.
  3. This class should extend ChangeNotifier (in package flutter/material.dart). This ChangeNotifier is responsible for "broadcasting" a notification to all widgets who are listening to changes in the state. 
  4. Our provider class must call "notifyListeners" each time the state changes. For example, if an item is added to the shopping cart, we should re-calculate the totals and call notifyListeners in the ChangeNotifier class.
Here is the complete class:

class CounterProvider extends ChangeNotifier
{
    int mCounter = 0;

    int getCurrentCount() => mCounter;
    void incrementCounter(){
      ++mCounter;
      // Since the state has changed, we must notify 
      notifyListeners();
    }

    void resetCount(){
      mCounter = 0;
      notifyListeners();
    }
}

Next, we need to add a ChangeNotificationProvider class into our widget hierarchy. This provider will be then be accessible to children in the hierarchy. The ChangeNotificationProvider takes two parameters; a function create which creates the provider and a child  . Here is how to inject the CNP into the hierarchy tree.

class MyApp extends StatelessWidget {
    const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
  
  	// NB: We wrap the UI hirearchy in a ChangeNotificationProvider class
    return ChangeNotifierProvider(
        create: (context) => CounterProvider(),
        child:   MaterialApp(
            title: 'Flutter Demo',
            theme: ThemeData(
              primarySwatch: Colors.blue,
            ),
            home: const MyHomePage(title: 'Flutter Demo Home Page'),
        ),
    );
  }
}

Finally, we need to access the state in the UI and also, the widget must be updated whenever the state changes (e.g an item is added to the cart). But how does the UI component listen to the state change events? 

Any widget that is a child (no matter how deep) of the ChangeNotificationProvider can get a handle to the state with a call to a Provider class. This Provider class is responsible of looking up the hierarchy and fetching the state of the specific class:

CounterProvider p;

@override
  Widget build(BuildContext context) {
    p = Provider.of<counterprovider>(context, listen:true );


Notice how we have passed the context and

Here is the complete code.


import 'package:flutter/material.dart';
import 'package:my_app/counter_provider.dart';
import 'package:provider/provider.dart';


void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
    const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
        create: (context) => CounterProvider(),
        child:   MaterialApp(
            title: 'Flutter Demo',
            theme: ThemeData(
              primarySwatch: Colors.blue,
            ),
            home: const MyHomePage(title: 'Flutter Demo Home Page'),
        ),
    );
  }
}



// ------------------------------------------------------------
class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  late CounterProvider p;

  void _increment(){
    p.incrementCounter();
  }

  @override
  Widget build(BuildContext context) {
    p = Provider.of<CounterProvider>(context, listen:true );
    int aCount = p.getCurrentCount();
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$aCount',
              style: Theme.of(context).textTheme.headline4,
            ),
            ElevatedButton(onPressed: () => p.resetCount(), child: const Text("Reset counter"),)
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _increment,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}



And the provider class

import 'package:flutter/material.dart';




class CounterProvider extends ChangeNotifier
{
    int mCounter = 0;

    int getCurrentCount() => mCounter;
    void incrementCounter(){
      ++mCounter;
      notifyListeners();
    }

    void resetCount(){
      mCounter = 0;
      notifyListeners();
    }
}

Monday, May 4, 2020

Parsing REST responses with Swift.

Hey Folks,

It's been a while since I did some blogging, so I thought I would break the hiatus with an article!

In this post, we will see how we can parse a JSON object which we receive. Typically, our Swift application would be talking to a service, which would return JSON data as the payload on an HTTPResponse, something like this:
    

    HTTP/1.1 200 OK
    X-Powered-By: Express
    Content-Type: application/json
    Date: Mon, 04 May 2020 18:51:34 GMT
    Connection: keep-alive
    Content-Length: 65
     ….

     {
        "emp_id": 20,
        "join_date": "2020-03-01T22:10:55.200Z",
        "given_name": "Vipul",
        "family_name": "Lal"
    }
        

Typically, we would need to parse the JSON data in the payload of the HTTP response using Swift. Fortunately, this is not very difficult using the Apple provided JSONDecoder class to parse the fields. 

In the example below, we have a simple Person class, which we will be parsing from a JSON string. 

The Person class has 4 variables:
  1. EmployeeID which is an integer value
  2. GivenName which is the Given Name
  3. Family Name
  4. Join Date which is a date. 
In order to parse the Person class using the Apple provider JSON parser, we have to implement the "Codeable" protocol like this:


    class Person: Codeable

Simply marking the class as Codeable will mean that it can be serialized and de-serialized by Swift. Note that Codeable is an overkill here because we will not be serializing the Person class in this example and we could have simply marked the class as Decodable.

When we make a class as Decodable, Swift library will be able to read in all the member fields. However, we expect that the "over-the-wire" fields of the HTTP Response to be different to the internal names of the Person object. For this, we need to have an enum extending the CodingKey protocol. The items of the enum will give the fields to expect in the JSON object. This gives us added flexibility and the on-the-wire format may be different to the internal field names.


    enum OverTheWire : CodingKey {
        case emp_id
        case given_name
        case family_name
        case join_date
    }

With the above enum, we would expect the field names to be "empty_id", "given_name" etc.

Finally, we declare an initializer which takes a Decoder as a parameter. We extract the fields from the decoder and construct the object from the over-the-wire JSON received.

Here is the entire code. You can create an empty "console" app using Xcode and paste the below code in a file.



//
//  main.swift
//  SerilazableTests
//
//  Created by Vipul Lal on 13/3/20.
//  Copyright © 2020 Far East Software. All rights reserved.
//

import Foundation

class Person : Codable{
    let mEmployeeId: Int?;
    var mGivenName: String?;
    var mFamilyName: String?
    var mJoinDate: Date?;
 
    // In order to have a different over-the-wire
    // format, we need to define an enul which implements
    // the CodingKey protocol
    
    enum OverTheWire : CodingKey {
        case emp_id
        case given_name
        case family_name
        case join_date
    }
    
    // Default init function...
    init(){
        self.mEmployeeId = -1;  // Mark instance as not-persisted.
    }
    
    // The seralize/deserailis
    required init( from decoder: Decoder  ) throws {    // required because our class is not a final class.
        do{
            let values = try decoder.container( keyedBy: OverTheWire.self );
            self.mEmployeeId = try values.decode( Int.self, forKey: .emp_id );
            self.mGivenName = try values.decode( String.self, forKey: .given_name );
            self.mFamilyName = try values.decode( String.self, forKey: .family_name );
            let dateStr = try values.decode( String.self, forKey: .join_date );
            let df = DateFormatter();
            df.dateFormat = "yyyy-MM-dd HH:mm:ss VV";
            self.mJoinDate = df.date( from: dateStr );
        }
        catch {
            print(" [\(error)] exception while extracting values from the wire format");
            throw error;
        }
    }
}



let wireData = """
    {
        "emp_id": 20,
        "join_date": "2020-03-01T22:10:55.200Z",
        "given_name": "Vipul",
        "family_name": "Lal"
    }
"""

let mockData:Data? = wireData.data(using: .unicode );
if let data = mockData {
    do{
        let jd = JSONDecoder()
        jd.dateDecodingStrategy = .iso8601;
        let p = try JSONDecoder().decode( Person.self, from: data );
        print("Yaay! We have a person called \(p.mGivenName) \(p.mFamilyName) ")
    }
    catch{
        print("\(error) while decoding person record.")
    }
}


Sunday, December 23, 2018

Observer pattern in Swift

Implementing an observer pattern in Swift can be tricky in Swift because Swift has automatic garage collection. This can lead to "retain cycles". What this means is that the observable has a reference to the observer and the observer has a reference to the observable, then neither object will be reclaimed, even if both objects go out of scope.

You can read about retain cycles here
Naturally, publishers of events are going to be running on a background thread and will be publishing events from the background thread. Please note that the below sample code is not suitable if your observers need to update the GUI. If you need to update the GUI, please change the dispatch mechanism to publish on the main thread.
Here is my solution

The key to the solution is to keep a weak reference in an array, indexed by the objectID of the observer in the observable. When we need to publish a notification to the observers, we check to see if the observer is still valid. If not, we remove it from the array, otherwise we send the notification.
 
// ------------------------------------------
//      MyObserverProtocol
// ------------------------------------------
protocol MyObserverProtocol: class {
    func onEvent();
}



//--------------------------------------------
//      EventGenerator class
// -------------------------------------------
class EventGenerator : NSObject
{
    // declare an internal structure which holds the weak reference to the
    // observer.
    struct ObserverRef{
        weak var m_Observer: MyObserverProtocol?;
    }
    
    // declare an dictionary of ObserverRef's. The key is an ObjectIdentifier, which is the
    // unique identifier assigned to every object automatically by Swift.
    private var m_Observers = [ ObjectIdentifier: ObserverRef ]();
    
    //---------------------------------------
    func addObserver(_ observer: MyObserverProtocol) {
        let id = ObjectIdentifier(observer);
        self.m_Observers[id] = ObserverRef( m_Observer:observer );
        print("Added Observer with \(id) into observers array...");
    }
    
    //---------------------------------------
    func removeObserver(_ observer: MyObserverProtocol) {
        let id = ObjectIdentifier(observer);
        self.m_Observers.removeValue(forKey: id);
    }

    
    //---------------------------------------
    func notifyObservers(){
        print("Event genrator called on thread \(Thread.current.debugDescription)");
        for (id, aObserver ) in self.m_Observers {
            if let observer = aObserver.m_Observer {
                observer.onEvent();
            }
            else{
                // observer did hara-kiri. remove it from the array
                print("EventGenerator: Observers with id: \(id) has died, removing from my observers list");
                self.m_Observers.removeValue(forKey: id);
            }
        }
    }
}


let m_SleepSec:UInt32 = 5;

// Declare a global observer...
let m_EventGenerator: EventGenerator = EventGenerator();


// -------------------------------------------
//  Simple observer class. 
// -------------------------------------------
class SomeObserver : MyObserverProtocol {
    let m_Name: String;
    
    init( name : String){
        self.m_Name = name;
    }
    
    func onEvent() {
        print("Yaay! I am \"\(m_Name)\" and I got a notification..." );
    }
}

// Global observer, should exist till the lifetime of the program.
let observer1: SomeObserver = SomeObserver( name: "Observer - 1" );
m_EventGenerator.addObserver(observer1)


// Simple testto check if the observer gets removed from the notifiers
func runTest1(){
    let observer2: SomeObserver = SomeObserver( name:"Observer - 2");
    m_EventGenerator.addObserver(observer2)
    //generate an asynchronous event..
    DispatchQueue.global(qos: .utility).async {
        // Asynchronous code running on the low priority queue
        m_EventGenerator.notifyObservers();
    }
    print("runTest1: Tests are running, main-thread going to sleep for \(m_SleepSec) sec ");
    sleep( m_SleepSec );     // 5 seconds. Enough time (hopefully) for the OS to schedule the task we set up above
    print("RunTest1 exiting..");
}

runTest1();

// generate an asynchronous event. This time, we should have only one observer, observer1
DispatchQueue.global(qos: .utility).async {
    // Asynchronous code running on the low priority queue
    m_EventGenerator.notifyObservers();
}
print("Tests are running, main-thread going to sleep for \(m_SleepSec) sec ");
sleep( m_SleepSec );
print("Main thread done..");  



Monday, November 7, 2011

Setting up a wifi network using your laptop/desktop

Always forgetting web-site passwords? Then, DataVault for Android is the application for you. 
Here is a link to the lite version. This version is free to try for 4 weeks.
And finally, here is a link to the full version.




Most of us have a broadband connection through which we connect to the internet. I use a lan cable to connect my laptop to the modem simply because it gives me the best connectivity. I don't use a wireless router at home. However, I recently bought an Android phone and wanted to download some applications. I did not want to invest in a data plan because I already had internet connectivity at home and office. However, I did want to download some games and tools for the Android. So, I set about setting a wireless network using my laptop. I have Windows 7 on my laptop and setting up a WLAN using my laptop was a breeze. Here are the steps you need to carry out to set up a wireless network at home so that you can connect your tablet or phone to the internet using an existing internet connection. First, open a command prompt - make sure that you run it with "administrator rights". To do this, go to Start --> All programs --> Accessories. Right click on the "Command Prompt" and select "Run as administrator". This should open up a command prompt like:
C:\windows\system32>
Next, type in the following (after changing 'VipulNetwork' and 'password' to your own values):
netsh wlan set hostednetwork mode=allow ssid='VipulNetwork' key='password'
You should see this:
The hosted network mode has been set to allow. The SSID of the hosted network has been successfully changed. The user key passphrase of the hosted network has been successfully changed.
Note, the password can be a string with 8 to 63 ASCII characters, eg. a passphrase, or 64 hexadecimal digits which represent 32 binary bytes.
Next, type in the following:
netsh wlan start hostednetwork
And this time you should see:
The hosted network started.
Just one more step before you can get your smartphone or tablet on to the internet... Finally, go to Start --> Control Panel --> Network and Sharing Center and click on 'Change adapter settings'. You should see all the network adapters installed on your machine. In my case, there are two network adapters:
  1. The LAN adapter (called Local Area Connection) and
  2. A 'Wireless Network Connection'.
  3. You should also see the 'pseudo' adapter called 'VipulNetwork' (or whatever name you gave it on the first 'netsh' command.
Since I connect to the internet using the LAN adapter, I right clicked on the adapter and went to 'Properties'. In the dialog box that pops up, select the 'Sharing' tab and make sure that the checkbox 'Allow other users to connect through this Internet connection'. Make sure that 'Home network connection' points to the network you just created. Finally, and I spent some time debugging this, make sure that in the 'Settings' dialog, at least the 'HTTPS' and the 'HTTP' services are checked. That's it! You should see the wireless lan that you just set up in your phone or tablet exactly as you would connect to another wireless lan. For Android phones, you can do the following to set up a persistent connection like this:
  1. Go to settings --> Wi-Fi settings -> Add Wi-Fi network.
  2. In the 'Add Wi-Fi network' dialog, enter the network name in the 'Network SSID' field, select Select the appropriate security mode (generally WAP/WAP2 PSK) and type in the password.
Now, your phone should be able to automatically discover and connect to the Wi-Fi hot-spot that you have created.
To turn off the hot-spot, simply turn off the wireless on the laptop.
Tech note: Windows 7 can share a physical wireless adapter and set up a 'virtual' adapter. This means that you should be able to use the same physical adapter to connect to the internet as well as create a wi-fi hot-spot - though I have not tried this (I don't have a wireless router - remember!)
Happy surfing from your tablet/smart-phone!!

Sunday, August 21, 2011

Common Android error messages


Always forgetting web-site passwords? Then, DataVault for Android is the application for you. 
Here is a link to the lite version. This version is free to try for 4 weeks.
And finally, here is a link to the full version.



Hi all. In this post I will try and share my pain, if you know what I mean!
Here are some common error messages thrown by Android and their possible causes and resolution:
  1. warning: found plain 'id' attribute; did you mean the new 'android:id' name?
    Means that your XML file has a plain id="..." somewhere. Please replace with android:id
  2. error: Error parsing XML: unbound prefix. This is a compile time error message that means that tour Tag is missing the namespace. Please add : xmlns:android="http://schemas.android.com/apk/res/android" to your start tag.
  3. Tip: To install ringtones into the emulator, create an /sdcard/media/audio/ringtones folder and then adb push /sdcard/media/audio/ringtones.
  4. If you get an error message like 'Error packaging final program: debug key expired on <date&gt, then simply rename the debug.keystore file. You can find the location of this file in the eclipse IDE from Windows/preferences/android/build.

Thursday, January 27, 2011

determine if a string is a palindrome or not

Always forgetting web-site passwords? Then, DataVault for Android is the application for you. 
Here is a link to the lite version. This version is free to try for 4 weeks.
And finally, here is a link to the full version.




Dammit, I'm mad!
The solution is to start comparing characters from the start of the string and the end of the string. Here is the function in it's entirety...
#include <iostream>

#include <cstring>


bool is_palindrome(const char *str)
{
    if( !str )
    {
        std::cout << "Parameter is null? Returning false\n";
        return false;
    }

    std::cout << "is_palindrome called '" << str << "'...\n";
    const char *end = ::strchr(str, '\0');
    while( end > str)
    {
        while(*str && !isalpha(*str) )
            ++str;
        while( !isalpha(*end) && end > str)
            --end;
        std::cout << "\tcomparing '" << *str << "' and " << *end << "'\n";
        if( tolower(*str) != tolower(*end))
            return false;
        ++str;
        --end;
    }
    return true;
}


int main(int argc, char **argv)
{
    std::cout << is_palindrome("hello") << "\n";
    std::cout << is_palindrome("A dog, a plan, a canal: pagoda.") << "\n";
    std::cout << is_palindrome("As I pee, sir, I see Pisa!  ") << "\n";
    std::cout << is_palindrome("Dentist? Sit Ned.") << "\n";
    return 0;
}


Sunday, February 14, 2010

Observer pattern

The Observer Pattern is classified under Object Behavioral Patterns in the book, Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma et al. (Addison-Wesley, 1995). In this article, I will be using the terms used by 'Gang of Four (GoF)' to explain Observer Pattern. First, let us understand the problem of object interaction.

GoF classifies the Observer Pattern as an Object Behavioral Pattern. The Observer Pattern is intended to "Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically". An object that is subjected to change is called a Subject and an object that depends on the Subject's state is called an Observer. In the above example, 'B' can be a Subject and Objects A and C can be Observers. A Subject can have any number of Observers. When the Subject changes its state, it Notifies all the Observers and the Observers query the Subject to maintain state consistency with the Subject.

Here is the code.

#include <iostream>
#include <list>
#include <algorithm>



/*
 * Code for the observer pattern
 *
 */


// fwd declare the classes
class Observer;
class Observable;

// Derive your class from this to
// get notifications in DataChanged
class Observer
{
    Observable *m_Observing;

public:
    Observer();
    virtual ~Observer();
    void AttachToObservable(Observable *);
    void UnhookFromObservable( );
    virtual void DataChanged( Observable * );

};

// Derive your class from Observable and call Notify
// whenever the data changes
class Observable
{
    typedef std::list>Observer *< ObserverList;
    typedef ObserverList::iterator ObserverList_Iter;

    ObserverList  m_Observers;

public:
    Observable();
    virtual ~Observable();
    void AddObserver(Observer *);
    void RemoveObserver(Observer *);
    void Notify();
};


Observable::Observable()
{
}

Observable::~Observable()
{
    ObserverList_Iter aIter;
    for( aIter = m_Observers.begin(); aIter != m_Observers.end();++aIter)
    {
        (**aIter).UnhookFromObservable();
    }
}

void Observable::AddObserver(Observer *o)
{
    ObserverList_Iter aIter;

    aIter = std::find( m_Observers.begin(), m_Observers.end(), o);
    if( aIter == m_Observers.end())
    {
        m_Observers.push_back( o);
    }
}


/*
 * This is called from the observer. We find the
 * observer in the list and remove the item.
 *
 */

void Observable::RemoveObserver(Observer *o)
{
    ObserverList_Iter aIter;

    aIter = std::find( m_Observers.begin(), m_Observers.end(), o);
    if( aIter != m_Observers.end())
    {
        m_Observers.erase( aIter );
    }
}


/*
 * Observable::Notify. Notify all the observers that
 * the data has changed.
 *
 */

void Observable::Notify()
{
    ObserverList_Iter aIter;

    for( aIter = m_Observers.begin(); aIter!= m_Observers.end(); ++aIter)
    {
        (**aIter).DataChanged( this );
    }
}

// ===============================================

Observer::Observer()
: m_Observing( NULL )
{
}

Observer::~Observer()
{
    // We are being destroyed. Make sure
    // we remove ourselves from the 
    // observer we attached ourself to.
    UnhookFromObservable();
}

void Observer::UnhookFromObservable()
{
    if( m_Observing )
    {
        m_Observing->RemoveObserver(this);
    }
    m_Observing = NULL;
}

void Observer::DataChanged(Observable*)
{
    std::cout << "Hey, you should override DataChanged in your derived class !!\n";
}

/*
 * In my line of work we price bonds off 
 * benchmark bonds. If the price of the 
 * benchmark bond changes, the price of all bonds
 * that are priced off that benchmark must be 
 * adjusted accordingly.
 *
 * Here is a simple class, Instrument that 
 * can be used for both the 
 * benchmark and the dependent bond. 
 *
 */
class Instrument : public Observable, public Observer
{
    double m_Price;
    double m_Spread;
    std::string m_ID;

public:
    Instrument( std::string & inID)
    : m_ID(inID), m_Price(0.0), m_Spread(10.0)
    {
    }
    Instrument(const char *p)
    : m_ID(p), m_Price(0.0)
    {
    }

    void PriceChanged( double inPrice )
    {
        m_Price = inPrice;
        Notify();
    }
    void DataChanged( Observable *o)
    {
        Instrument *i = dynamic_cast(o);
        if(i)
        {
            std::cout << m_ID << " price updated from " << i->m_ID << "\n";
            this->m_Price = i-<m_Price + m_Spread;
        }
    }
};


void test1()
{
    Instrument  i1( "FGBLZ0");
    Instrument  i2( "DBS bank 2010");

    i1.AddObserver( &i2 );
    i1.PriceChanged( 100);

}


int main(int, char **)
{
    std::cout << "Hello, world!\n";

    test1();

    return 0;
}

// EOF

Sunday, February 7, 2010

Producer consumer

A common programing problem is program while writing performant client-server applications is to have multiple threads service client requests and data. This increases the effeftive throughput, expecially if the processing requires I/O to/from a slow device. With such a scenarion, having multiple threads to service client requests dramatically improves the thruput because if a thread is blocked for i/o, other threads can start processing on other requests.

In this blog, I present the code for a simple queuing mechanism.

First, we define some utility classes.

Locker is a convenient class to automatically lock and unlock a mutex. It is designed for exception safety. We lock the mutex in the constructor and unlock in the destructor.

The next class is a convenient class to start, stop and join threads. Note, that this class is a simple wrapper and it is not well designed for portabality. In the implementation here, we assume that we are using POSIX threads and all threads are daemon threads (daemon threads terminate when the app terminates as opposed to joinable threads, which have to terminate before the app is terminated by the OS.

Subclasses of this class must override the ThdFunc, which is the main thread function.

Note that there is a race condition in this arrangement. If we create the underlying pthread in the constructor itself, sometimes the ThdFunc gets called even before the constructor of MyThreadBase has finished ! Since the ThdFunc is a pure virtual function, we get a system "Null pointer exception! Therefore, the underlying thread is created in the start call, which can only be made when the constructor returns and the object is fully constructed by that time.


class MyThreadBase
{
protected:
    static void *startFunc(void *);

    pthread_t  m_thread;
    bool m_KeepRunning;
    bool m_isDaemon;

public:

    MyThreadBase(bool isDaemon = true );


    virtual ~MyThreadBase();

    void start();

    void kill();
    void join();

    virtual void ThdFunc() = 0;

    bool KeepRunning() {return m_KeepRunning; }
    void SetTerminateFlag() { m_KeepRunning = false;}
};

Here is the code in its entirety

#include <iostream>
#include <list>
#include <pthread.h>


using namespace std;

// Convenient class to make sure the
// mutex is unlocked even if there is 
// an exception.
struct Locker
{

    Locker(pthread_mutex_t & inMutex)
    : m_Mutex(inMutex)
    {
        ::pthread_mutex_lock( &m_Mutex);
    }

    ~Locker()
    {
        ::pthread_mutex_unlock( &m_Mutex );
    }

private:
    pthread_mutex_t & m_Mutex;
};



// This is the bonded-queue class. In the 
// example we use a list to store elements
// because we can remove items from the 
// front of the queue. We could have used a
// dqueue also. We did not want to use a vector
// because removing an item from the front of
// the vector will force a copy of all subsequent
// items in the vector. However, if you were using
// pointers to messages, then a vector would be
// more efficiend. Ideally, this class should
// be a template class and the data type should
// be a vector of shared_ptr

#define QUEUE_SIZE  10

class BQueue
{
    list m_Items;
    pthread_mutex_t  m_QueueMutex;
    pthread_cond_t   m_EmptyCond;   // wait on this while trying to read
    pthread_cond_t   m_FullCond;  // wait on this while trying to write
public:

    BQueue();
    ~BQueue();
    void  AddItem(int inItem);
    int   RemoveItem();
};

BQueue::BQueue()
{
    //m_Items.resize( QUEUE_SIZE );
    ::pthread_mutex_init( &m_QueueMutex, NULL );
    ::pthread_cond_init( &m_EmptyCond, NULL );
    ::pthread_cond_init( &m_FullCond, NULL );
}

BQueue::~BQueue()
{
}


int BQueue::RemoveItem()
{
    Locker w(m_QueueMutex);
    while( m_Items.empty() )
    {
        ::pthread_cond_wait( &m_EmptyCond, &m_QueueMutex );
    }
    int aRet = m_Items.front();
    m_Items.pop_front();
    ::pthread_cond_signal( &m_FullCond );
    return aRet;
}


void BQueue::AddItem(int inValue)
{
    Locker w( m_QueueMutex );
    while( m_Items.size() >= QUEUE_SIZE )
    {
        cout << "BQueue::AddItem, queue is full!\n";
        ::pthread_cond_wait( &m_FullCond, &m_QueueMutex);
    }

    m_Items.push_back( inValue );
    ::pthread_cond_signal( &m_EmptyCond );
}





class MyThreadBase
{
protected:
    static void *startFunc(void *);

    pthread_t  m_thread;
    bool m_KeepRunning;
    bool m_isDaemon;

public:

    MyThreadBase(bool isDaemon = true )
    : m_thread(0),
    m_KeepRunning(true),
    m_isDaemon( isDaemon )
    {
    }


    virtual ~MyThreadBase()
    {
    }

    void start()
    {
        // assert( m_thread == NULL );
        // This code is not exception safe.
        // We will have a memory leak if we
        // do not call pthread_attr_destroy

        ::pthread_attr_t attr;
        ::pthread_attr_init( &attr );
        ::pthread_attr_setdetachstate( &attr, m_isDaemon );
        ::pthread_create( &m_thread, &attr, startFunc, this );
        ::pthread_attr_destroy( &attr );
    }

    void kill()
    {
        m_KeepRunning = false;
        ::pthread_cancel( m_thread );
    }

    void join()
    {
        m_KeepRunning = false;
        ::pthread_join( m_thread, NULL );
    }

    virtual void ThdFunc() = 0;

    bool KeepRunning() {return m_KeepRunning; }
    void SetTerminateFlag() { m_KeepRunning = false;}
};

void * MyThreadBase::startFunc(void *p)
{
    MyThreadBase* ap( static_cast(p));
    try
    {
        ap->ThdFunc();
    }
    catch(...)
    {
        cout << "Exception caught in startFunc\n";
    }
    return NULL;
}

// Consumer threads pull off requests from
// the queue and process them.
class ConsumerThread: public MyThreadBase
{
    BQueue & m_Queue;

public:
    ConsumerThread(BQueue & inQ):MyThreadBase(true), m_Queue(inQ)
    {
    }

    ~ConsumerThread()
    {
    }

    void ThdFunc()
    {
        cout << "Hello, I am a consumer thread!\n";
        while( KeepRunning() )
        {
            int aData = m_Queue.RemoveItem();
            cout << "Data item is " << aData << "\n";
        }

    }

};

// Producer threads produce data and put into
// the queue.
class ProducerThread: public MyThreadBase
{

    bool m_Done;
    BQueue & m_Queue;

public:
    ProducerThread(BQueue & inQ ):
    MyThreadBase(true), m_Done(false), m_Queue(inQ)
    {
    }

    ~ProducerThread()
    {
    }

    bool done() {return m_Done ;}

    void ThdFunc()
    {
        for(int i=0; i< 100; i++)
        {
            cout << "Producer Thread: Adding item " << i << "\n";
            m_Queue.AddItem(  i );
        }
        m_Done = true;

    }

};


#define MAX_CONSUMERS 5
#define MAX_PRODUCERS 1


int main(int, char **)
{
    cout << "Hello world!\n";
    cout << "Bonded queue simulation. Please enter the following data...\n";


    BQueue a_Queue;

    ConsumerThread * ct[ MAX_CONSUMERS ];

    for(int i=0;i< MAX_CONSUMERS ;i++)
    {
        ct[i] = new ConsumerThread( a_Queue );
        ct[i]->start();
    }
    cout << "Consumer threads created!!\n";

    ProducerThread aProducer( a_Queue );
    aProducer.start();
    while(! aProducer.done() )
    {
        cout << "Main thread. Producer is not yet done!\n";
        ::sleep(10);
    }

    cout << "deleting all the threads...\n";

    for(int i=0;i< MAX_CONSUMERS ;i++)
    {
        ct[i]->kill();
        delete ct[i] ;
    }

}

Tuesday, January 12, 2010

C++ Algorithms summary

The following functions are defined in or , and are part of the std namespace.

accumulate sum up a range of elements

adjacent_difference compute the differences between adjacent elements in a range

adjacent_find finds two identical (or some other relationship) items adjacent to each other.

  FI adjacent_find(FI first, FI last);
  FI adjacent_find( FI first, FI last, Pred p);

binary_search determine if an element exists in a certain range

copy copy some range of elements to a new location

copy_backward copy a range of elements in backwards order

count return the number of elements matching a given value

count_if return the number of elements for which a predicate is true

equal determine if two sets of elements are the same

equal_range search for a range of elements that are all equal to a certain element

fill assign a range of elements a certain value

fill_n assign a value to some number of elements

find find a value in a given range

find_end find the last sequence of elements in a certain range

find_first_of search for any one of a set of elements

find_if find the first element for which a certain predicate is true

for_each apply a function to a range of elements

generate saves the result of a function in a range

generate_n saves the result of N applications of a function

includes returns true if one set is a subset of another

inner_product compute the inner product of two ranges of elements

inplace_merge merge two ordered ranges in-place

is_heap returns true if a given range is a heap

iter_swap swaps the elements pointed to by two iterators

lexicographical_compare returns true if one range is lexicographically less than another

lower_bound search for the first place that a value can be inserted while preserving order

make_heap creates a heap out of a range of elements

max returns the larger of two elements

max_element returns the largest element in a range

merge merge two sorted ranges

min returns the smaller of two elements

min_element returns the smallest element in a range

mismatch finds the first position where two ranges differ

next_permutation generates the next greater lexicographic permutation of a range of elements

nth_element put one element in its sorted location and make sure that no elements to its left are greater than any elements to its right

partial_sort sort the first N elements of a range

partial_sort_copy copy and partially sort a range of elements

partial_sum compute the partial sum of a range of elements

partition divide a range of elements into two groups

pop_heap remove the largest element from a heap

prev_permutation generates the next smaller lexicographic permutation of a range of elements

push_heap add an element to a heap

random_shuffle randomly re-order elements in some range

remove remove elements equal to certain value

remove_copy copy a range of elements omitting those that match a certain value

remove_copy_if create a copy of a range of elements, omitting any for which a predicate is true

remove_if remove all elements for which a predicate is true

replace replace every occurrence of some value in a range with another value

replace_copy copy a range, replacing certain elements with new ones

replace_copy_if copy a range of elements, replacing those for which a predicate is true

replace_if change the values of elements for which a predicate is true

reverse reverse elements in some range

reverse_copy create a copy of a range that is reversed

rotate move the elements in some range to the left by some amount

rotate_copy copy and rotate a range of elements

search search for a range of elements

search_n search for N consecutive copies of an element in some range

set_difference computes the difference between two sets

set_intersection computes the intersection of two sets

set_symmetric_difference computes the symmetric difference between two sets

set_union computes the union of two sets

sort sort a range into ascending order

sort_heap turns a heap into a sorted range of elements

stable_partition divide elements into two groups while preserving their relative order

stable_sort sort a range of elements while preserving order between equal elements

swap swap the values of two objects

swap_ranges swaps two ranges of elements

transform applies a function to a range of elements

unique remove consecutive duplicate elements in a range

unique_copy creates a copy of some range of elements that contains no consecutive duplicates

upper_bound searches for the last place that a value can be inserted while preserving order (first place that is greater than the value)

Thursday, November 19, 2009

C++ cast operators

Describe C++ cast operators

static_castis used to cast up and down the class hierarchy, conversions with unary constructors as well as conversions with conversion operators. It is similar to the C-style casts.

For instance, in the code below, a call is made to the operator int in class X

dynamic_cast is the C++ way of casting. It uses RTTI to determine if the cast is valid.

If we are attempting to cast to an incompatible pointer type, the result is a NULL.

If we try to cast to an incompatible reference type, an std::bad_cast exception is thrown.

The dynamic_cast must be un-ambigous.

dynamic_cast works only with polymorphic types (ie where the classes have at least one virtual function)

struct X
 {
     int value;
     virtual ~X() {}
 };

 struct Y : public X
 {
 };


 int main(int, char **)
 {
     Y anY;
     X anX;

     X & xRef = anY;
     Y& yRef = dynamic_cast( xRef );

     X& xRef2 = anX;
     try
     {
         Y& yRef2 = dynamic_cast( xRef2 );
     }
     catch( std::bad_cast&  e)
     {
         std::cout <<"Caught bad cast exception ! " << e.what() << "\n";
     }
     std::cout << "Program finished !\n";
     return 0;
 }


reinterpret_castAllows you to cast apples to horses.

const_castallows us to cast away the const or volatile from a reference or pointer. The target data type must be the same as the source type.


Thursday, November 12, 2009

Delegates and events in C#

What are delegates and events in C# ? Delegates

Delegates in C# are objects which points towards a function which matches its signature. Delegates are reference type used to encapsulate a method with a specific signature. Delegates are similar to function pointers in C++; however, delegates are type-safe and secure.

Here are some features of delegates:

  • A delegate represents a class.
  • A delegate is type-safe.
  • We can use delegates both for static and instance methods
  • We can combine multiple delegates into a single delegate.
  • Delegates are often used in event-based programming, such as publish/subscribe.
  • We can use delegates in asynchronous-style programming.
  • We can define delegates inside or outside of classes.
  • Delegte declarations are like ordinary declerations and can be public, private internal etc.
  • Two delegates are compatible if their parameters are of the same type, order and modifiers and their return types are the same.
  • Delegates can be combined using the + and += operators. When two delegates are combined, the resulting delegate contains all the callable entities from both the delegates. Similarily, delegates can be removed using the - or -= operators.
  • Delegates can be compared.
  • delegate methods are invoked synchronously.
  • If such a delegate invocation includes reference parameters, each method invocation will occur with a reference to the same variable and changes to that variable by one method in the invocation list will be visible to methods further down the invocation list.
  • If the delegate invocation includes output parameters or a return value, their final value will come from the invocation of the last delegate in the list.
  • If an exception occurs within a delegate and the exception is not caught in the method that was called, continues in the method that called the delegate. If the exception is not handled in the called method, delegate processing is abandoned and other functions in the delegate are not called.

To declare a delegate, use the delegate keyword like:

    // declare a delegate
    public delegate void MyDelegate(int x); 

    /*
     * Declare a function which takes a 
     * delegate parameter. 
     */
    void MyFunc( MyDelegate inDelegateParam)
    {
         inDelegateParam(100); // Call the delegate
    }

    // Create a function with the same signature 
    // as the delegate decl
    void someFunc(int p)
    {
    }

    static void Main(string[] args)
    {
        MyDelegate aDel = new MyDelegate( someFunc);
        MyFunc( aDel );
    }

When we declare a delegate, the compiler automatically creates a class derrived from System.Delegate. A delegate instance encapsulates one or more methods, each of which is a callable entiry. For instance methods, the callable entity consists of the instance and the method.

When we invoke a delegate, all the callable entities get called.

Events

Delegates are used to create events. here is an example of an event

        // First declare a delegate
        public delegate void MyDelegate(int x);

        // now, the event
        public static event MyDelegate m_del;

        public static void testit()
        {
            m_del += new MyDelegate(EventFunc);
            m_del(2);
        }

        // This is the event handler
        static void EventFunc(int x)
        {
            Console.WriteLine("in event handler!!!!\n");
        }

Thursday, November 5, 2009

Singleton in multi-threaded environment

Question: How would you write a singleton in a multi-threaded environment?

In a singleton, there are two race conditions; one where the instance is created and the other when we access instance data. The method which creates the singleton instance must be made thread safe. Here is an example:

Wednesday, October 14, 2009

Reversing a single linked list

Question :How do you reverse a list?
Ans:
void reverselist(void)
{
    if(head==0)
        return;
    if(head->next==0)
        return;
    if(head->next==tail)
    {
        head->next = 0;
        tail->next = head;
    }
    else
    {
        node* pre = head;
        node* cur = head->next;
        node* curnext = cur->next;
        head->next = 0;
        cur->next = head;
        for(; curnext!=0; )
        {
            cur->next = pre;
            pre = cur;
            cur = curnext;
            curnext = curnext->next;
        }
        curnext->next = cur;
    }
}


Wednesday, September 2, 2009

Functors

Summary A Function Object, or Functor (the two terms are synonymous) is simply any object that can be called as if it is a function. An ordinary function is a function object, and so is a function pointer; more generally, so is an object of a class that defines operator(). Description

The basic function object concepts are Generator, Unary Function, and Binary Function. For example, a generator can be called as f(), Unary function as f(x), and binary function as f(x,y). All other function object concepts defined by the STL are refinements of these three. Function objects that return bool are an important special case.

A Unary Function whose return type is bool is called a Predicate, and a Binary Function whose return type is bool is called a Binary Predicate.

There is an important distinction, but a somewhat subtle one, between function objects and adaptable function objects. In general, a function object has restrictions on the type of its argument. The type restrictions need not be simple, though: operator() may be overloaded, or may be a member template, or both. Similarly, there need be no way for a program to determine what those restrictions are. An adaptable function object, however, does specify what the argument and return types are, and provides nested typedefs so that those types can be named and used in programs. If a type F0 is a model of Adaptable Generator, then it must define F0::result_type. Similarly, if F1 is a model of Adaptable Unary Function then it must define F1::argument_type and F1::result_type, and if F2 is a model of Adaptable Binary Function then it must define F2::first_argument_type, F2::second_argument_type, and F2::result_type. The STL provides base classes unary_function and binary_function to simplify the definition of Adaptable Unary Functions and Adaptable Binary Functions. [2] Adaptable function objects are important because they can be used by function object adaptors: function objects that transform or manipulate other function objects. The STL provides many different function object adaptors, including unary_negate (which returns the logical complement of the value returned by a particular AdaptablePredicate), and unary_compose and binary_compose, which perform composition of function object. Finally, the STL includes many different predefined function objects, including arithmetic operations (plus, minus, multiplies, divides, modulus, and negate), comparisons (equal_to, not_equal_to greater, less, greater_equal, and less_equal), and logical operations (logical_and, logical_or, and logical_not). It is possible to perform very sophisticated operations without actually writing a new function object, simply by combining predefined function objects and function object adaptors.

Wednesday, July 29, 2009

Everything about virtual functions

  • A class that declares or inherits a virtual function is called a polymorphic class
  • A virtual funtion ensures dynamic binding.
  • If a function is declared virtual, then if we have a function with the same name and parameters in a derrived class, then that function is automatically virtual, even if we do not declare it as virtual in the derrived class.
     struct A
     {
        virtual void f()
        {
           cout << "A::f()";      
        }    
    }     
    struct B : A    
    {        
        void f( int )      
        {         
           cout << "B::f()";     // Hides A:f()
        }    
    }     
    struct C: B    
    {        
        void f()      
        {          
            cout <<"C::f()";     // This is always virtual
        }    
    }   
    

    In the above example, B::F(int) hides A:f(). A b; b.f is illegal.

    Also, C::F() is implicitly virtual.

  • If a funcion has the same name as the base class function and different parameters, then it hides all functions with the same name in the base class. In the Example 1 above, B::f hides A:f
  • The return type of a virtual function may be different from the overridden one. This is called covarent virtual function. The return types may differ provided all the following conditions are met:

    1. If A::func returns a pointer or reference of type T, then B:func can return only a direct or un-ambigous derrived class from T

    2. The const or volatile qualifier of type returned by B is at lease as restrictive as A

    3. The return type of B::func must be complete and accessible at the point or it may be a B.

  • We can call a base classes virtual function by base::func().
  • A virtual function can be == 0, or pure virtual. Instances of abstract classes can not be created and an abstract class can not be used as parameters to templates.
  • A derrived class can be abstract, even if it is derrived from a non-abstract class.
  • We can pass a pointer or reference to an abstract class as a parameter in a function. In that function, we can even call a pure virtual method. However, we can not have an instance of an abstract class as a parameter.
  • We can override a virtual function with an abstract function in a derrived class.

Everything about constructors

  1. Everything you wanted to know about constructors
    • Constructors are used to initialize objects.
    • When a class derives from other classes, the constructors are called in the following order.
      • Virtual base classes, left to right in the class decleration
      • base classes, left to right in the class decleration
      • Member classes and references
      • Finally, the body of the constructor is executed.
    • A copy constructor is a constructor which takes a const reference of type self and is used to construct a copy of the instance. A copy constructor is used extensively by STL containers and algorithms.
    • A constructor must not leak memory, even if any of the constructors of base or member classes throws an exception.
    • A default constructor is a constructor which takes no arguments, or a constructor which has default values for all arguments. If we dont define any constructor in our class, then the compiler automatically creates a default constructor for our class
    • If we make the constructor of a class private, then an instance of the class can not be created directly. We often use this to create a singleton pattern.
    • If you have a reference member, then the only way for you to initialize the reference is in the constructor. If your class has pointers, then you should always initialize the pointer to NULL in the constructor.

Monday, July 27, 2009

Using Expat to parse XML

Socket programming

Sockets are endpoints in communication. We create a socket on the server application and sit and listen for incomming connections. Clients initiate a connection and send data once the connection is established.

There are two types of sockets; connected and datagram sockets. Connected sockets keep the connection between the client-server. With datagram sockets, there is no gurantee of delivery of packet and we have to use packet counting mechanism if we want to gurantee delivery of data. However, datagram sockets are less resource intensive and can be used with applications like media streaming applications.

Let us look at connection oriented sockets.

For the server side, the basic steps are:

  • Create a socket (int aSocket = ::socket(...) )
  • Bind the socket to an address and port
  • Call accept in a loop to listen to connection requests. This call blocks until there is a connection request. On return, the OS returns a socket which we use to communicate with the client application (see example)

On the client side, we create a socket simply call connect and we are off.

Data structures used:

1. sockaddr and sockaddr_in are used to specify the host and port we want to connect to. Both these structures are of the same size. All networking calls where we need to specify an address take a pointer to a sockaddr structure as a parameter. With TCP/IP sockets, we fill in a sockaddr_in structure and typecast it to a sockaddr structure in calls to networking functions.


typedef uint32_t in_addr_t;

struct in_addr
{
  in_addr_t s_addr;
};

struct sockaddr_in
{
  sa_family_t sin_family;
  in_port_t sin_port;
  struct in_addr sin_addr;

  unsigned char __pad[16 - sizeof(short int)
   - sizeof(unsigned short int) - sizeof(struct in_addr)];
};

The following functions can be used to convert dotted (127.0.0.1) to binary and vice-versa:

    #include 
    in_addr_t inet_addr(const char *cp);
    char *inet_ntoa(struct in_addr in);

--more stuff to follow ---

Using the select command

Typically, on the server side, we would have several sockets which we would read and write data to. We use the select function to determine which sockets we can read and/or write to without the call blocking.

The select call takes the following parameters:

   int select(int maxFD, fd_set *read, 
              fd_set *write, 
              fd_set *exceptions, 
              struct timeval *tv);

where:

  • The first parameter, i.e. maxFD in the above call is the highest number +1 of descriptor in read, write and except set we are interested in. For example, if we currently have sockets 4,7 and 9 open and we wish to read from any one of these, we would pass 10 as the first argument to select call.
  • read, write and ex in the call above are pointers to three fd_set structures which specify the sockets we are interested in. This structure is described below. Any or all of these parameters can be null. For example, if we are only interested in determining which sockets have data to read, we would pass NULL for the write and exceptions sets. We use the FD_SET, FD_CLR calls to set, clear individual sockets and FD_ZERO to zero out the entire set. FD_ISSET is used to determine which sockets are ready (see example below).
  • The timeval struct gives the number of seconds to wait before returning. This argument can be used to specify an indefinite wait, or a definite wait time, as described below.
  • The return value is the total number of descriptors that are ready, with -1 representing an error condition, 0 means that the call timed out before any of the descriptors became ready, etc.

The fd_set structure is simply a bit map with each bit representing an integer value. For example, if we use the FD_SET macro like FD_SET( 4,&readFD), bit 4 in the readFD will be set.

The struct timeval is as follows:

    struct timeval
    {
        long tv_sec;
        long tv_usec;
     };

where tv_sec and tv_usec specify the seconds and microseconds to wait.

  • If the tv parameter is null, then the kernal will wait forever until a socket does become ready.
  • If both tv_sec and tv_usec are zero, then the call will return immediately.
  • If either of these parameters is non-zero, then the call will wait for the specified interval. We can then use the return value from this call to check if any of the sockets are ready. The POSIX specs allow the call to modify this struct, so remember to reset the values before each call.

If a bit is set on the exception set, that indicates the arrival of out-of-band data.

Note that setting a socket in the non-blocking mode will not affect the way select works. So, even if all the sockets in the read set are non-blocking, the select call will wait as specified by the tv parameter.

Producer-Consumer using Windows threading

Here is a simple solution to the producer-consumer problem using Windows threading. Basic classes are
  • Producer This is the thread that produces jobs at random intervals
  • Consumer This is the thread that pulls jobs off the messageQueue and processes the job. There are multiple consumers.
  • MessageQueue Fixed size queue to hold the jobs
  • Job Abstract job class that the Consumer consumes
  • Thread Utility class to manage trreads