text:
using namespace BloombergLP;
using namespace bsl;  // automatically added by script

//=============================================================================
//                              TEST PLAN
//-----------------------------------------------------------------------------
//                              Overview
//                              --------
// The component under test is a container of Observers that forwards records
// and their corresponding publication contexts to the contained observers.  We
// must ensure that the component behaves correctly as both a container of
// Observers and a re-layer of records and contexts.
//-----------------------------------------------------------------------------
// [ 2] ball::MultiplexObserver(bslma::Allocator *ba = 0);
// [ 2] ~ball::MultiplexObserver();
// [ 4] void publish(const ball::Record& rec, const ball::Context& ctxt);
// [ 5] void publish(const bsl::shared_ptr<const ball::Record>& rec,
//                   const ball::Context&                       ctxt);
// [ 5] void releaseRecords();
// [ 3] int registerObserver(ball::Observer *observer);
// [ 3] int deregisterObserver(ball::Observer *observer);
// [ 3] int numRegisteredObservers() const;
//-----------------------------------------------------------------------------
// [ 1] BREATHING TEST
// [ 6] USAGE EXAMPLE

// ============================================================================
//                     STANDARD BDE ASSERT TEST FUNCTION
// ----------------------------------------------------------------------------

namespace {

int testStatus = 0;

void aSsErT(bool condition, const char *message, int line)
{
    if (condition) {
        cout << "Error " __FILE__ "(" << line << "): " << message
             << "    (failed)" << endl;

        if (0 <= testStatus && testStatus <= 100) {
            ++testStatus;
        }
    }
}

}  // close unnamed namespace

// ============================================================================
//               STANDARD BDE TEST DRIVER MACRO ABBREVIATIONS
// ----------------------------------------------------------------------------

#define ASSERT       BSLIM_TESTUTIL_ASSERT
#define ASSERTV      BSLIM_TESTUTIL_ASSERTV

#define LOOP_ASSERT  BSLIM_TESTUTIL_LOOP_ASSERT
#define LOOP0_ASSERT BSLIM_TESTUTIL_LOOP0_ASSERT
#define LOOP1_ASSERT BSLIM_TESTUTIL_LOOP1_ASSERT
#define LOOP2_ASSERT BSLIM_TESTUTIL_LOOP2_ASSERT
#define LOOP3_ASSERT BSLIM_TESTUTIL_LOOP3_ASSERT
#define LOOP4_ASSERT BSLIM_TESTUTIL_LOOP4_ASSERT
#define LOOP5_ASSERT BSLIM_TESTUTIL_LOOP5_ASSERT
#define LOOP6_ASSERT BSLIM_TESTUTIL_LOOP6_ASSERT

#define Q            BSLIM_TESTUTIL_Q   // Quote identifier literally.
#define P            BSLIM_TESTUTIL_P   // Print identifier and value.
#define P_           BSLIM_TESTUTIL_P_  // P(X) without '\n'.
#define T_           BSLIM_TESTUTIL_T_  // Print a tab (w/o newline).
#define L_           BSLIM_TESTUTIL_L_  // current Line number

// ============================================================================
//                  NEGATIVE-TEST MACRO ABBREVIATIONS
// ----------------------------------------------------------------------------

#define ASSERT_SAFE_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_PASS(EXPR)
#define ASSERT_SAFE_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_FAIL(EXPR)
#define ASSERT_PASS(EXPR)      BSLS_ASSERTTEST_ASSERT_PASS(EXPR)
#define ASSERT_FAIL(EXPR)      BSLS_ASSERTTEST_ASSERT_FAIL(EXPR)
#define ASSERT_OPT_PASS(EXPR)  BSLS_ASSERTTEST_ASSERT_OPT_PASS(EXPR)
#define ASSERT_OPT_FAIL(EXPR)  BSLS_ASSERTTEST_ASSERT_OPT_FAIL(EXPR)

//=============================================================================
//                             USAGE EXAMPLE
//-----------------------------------------------------------------------------

// my_ostreamobserver.h

class my_OstreamObserver : public ball::Observer {
    ostream& d_stream;

  public:
    explicit my_OstreamObserver(ostream& stream) : d_stream(stream) { }
    ~my_OstreamObserver() { }
    void publish(const ball::Record&  record,
                 const ball::Context& context);
};

// my_ostreamobserver.cpp

void my_OstreamObserver::publish(const ball::Record&  record,
                                 const ball::Context& context)
{

    switch (context.transmissionCause()) {
      case ball::Transmission::e_PASSTHROUGH: {
        d_stream << "Single Passthrough Message:" << endl;
      } break;
      case ball::Transmission::e_TRIGGER_ALL: {
        d_stream << "Remotely ";      // no 'break'; concatenated output
      }
      case ball::Transmission::e_TRIGGER: {
        d_stream << "Triggered Publication Sequence: Message ";
        d_stream << context.recordIndex() + 1  // Account for 0-based index.
                 << " of " << context.sequenceLength() << endl;
      } break;
      default: {
        d_stream << "***ERROR*** Unknown Message Cause:" << endl;
      } break;
    }

    d_stream << "\tTimestamp:  " << record.fixedFields().timestamp() << endl;
    d_stream << "\tProcess ID: " << record.fixedFields().processID() << endl;
    d_stream << "\tThread ID:  " << record.fixedFields().threadID()  << endl
             << endl;
}

//=============================================================================
//                  GLOBAL TYPEDEFS/CONSTANTS FOR TESTING
//-----------------------------------------------------------------------------

typedef ball::MultiplexObserver Obj;

typedef ball::Context           Ctxt;
typedef ball::Record            Rec;
typedef ball::RecordAttributes  Attr;
typedef ball::TestObserver      TestObs;

const int SEQUENCE_LENGTH = 99;

//=============================================================================
//                  GLOBAL HELPER FUNCTIONS FOR TESTING
//-----------------------------------------------------------------------------

// The following three helper functions are used to test 'publish' (case 4).

static int nextRecord(ball::Record& record)
    // Modify the specified 'record' to have a value distinct from any other
    // record transmitted so far in the publication sequence and return the
    // 0-based sequence number of 'record'.
{
    static int sequenceNumber = 0;

    ball::RecordAttributes attr;
    attr.setLineNumber(sequenceNumber);
    attr.setProcessID(sequenceNumber);
    attr.setSeverity(sequenceNumber);
    attr.setThreadID(sequenceNumber);
    record.setFixedFields(attr);

    return sequenceNumber++;
}

static int isNthRecord(const ball::Record& record, int nth)
    // Return 1 if the specified 'record' is the specified 'nth' in the
    // publication sequence, and 0 otherwise.
{
    const ball::RecordAttributes& attr = record.fixedFields();

    if (nth == attr.lineNumber()
     && nth == attr.processID()
     && nth == attr.severity()
        && nth == static_cast<int>(attr.threadID())) {
        return 1;                                                     // RETURN
    }
    else {
        return 0;                                                     // RETURN
    }
}

static int isNthContext(const ball::Context& context, int nth)
    // Return 1 if the specified 'context' is the specified 'nth' in the
    // publication sequence, and 0 otherwise.
{
    if (ball::Transmission::e_TRIGGER == context.transmissionCause()
        &&                     nth == context.recordIndex()
        &&         SEQUENCE_LENGTH == context.sequenceLength()) {
        return 1;                                                     // RETURN
    }
    else {
        return 0;                                                     // RETURN
    }
}

// ============================================================================
//                               TEST APPARATUS
// ----------------------------------------------------------------------------
// skong: REMOVE THIS after it is moved to the ball::TestObserver

class TestAsyncObserver : public ball::Observer {
    // DATA
    bsl::ostream& d_stream;       // target of 'publish' method
    ball::Record  d_record;       // most-recently-published record
    ball::Context d_context;      // most-recently-published context
    int           d_numRecords;   // total number of published records
    int           d_numClears;    // total number of 'clear' called

    // NOT IMPLEMENTED
    TestAsyncObserver(const TestAsyncObserver&);
    TestAsyncObserver& operator=(const TestAsyncObserver&);

  public:
    // CREATORS
    explicit TestAsyncObserver(bsl::ostream&     stream,
                               bslma::Allocator *basicAllocator = 0);

    virtual ~TestAsyncObserver();

    // MANIPULATORS
    virtual void publish(const bsl::shared_ptr<const ball::Record>&  record,
                         const ball::Context&                        context);

    virtual void releaseRecords();

    // ACCESSORS
    int numPublishedRecords() const;

    int numClears() const;

    const ball::Record& lastPublishedRecord() const;

    const ball::Context& lastPublishedContext() const;
};

// CREATORS
inline
TestAsyncObserver::TestAsyncObserver(bsl::ostream&     stream,
                                     bslma::Allocator *basicAllocator)
: d_stream(stream)
, d_record(basicAllocator)
, d_context(basicAllocator)
, d_numRecords(0)
, d_numClears(0)
{
}

TestAsyncObserver::~TestAsyncObserver()
{
}

// MANIPULATORS
void TestAsyncObserver::publish(
                            const bsl::shared_ptr<const ball::Record>& record,
                            const ball::Context&                       context)
{
    d_record  = *record;
    d_context = context;
    ++d_numRecords;
}

void TestAsyncObserver::releaseRecords()
{
    ++d_numClears;
}

// ACCESSORS
inline
int TestAsyncObserver::numPublishedRecords() const
{
    return d_numRecords;
}

inline
int TestAsyncObserver::numClears() const
{
    return d_numClears;
}

inline
const ball::Record& TestAsyncObserver::lastPublishedRecord() const
{
    return d_record;
}

inline
const ball::Context& TestAsyncObserver::lastPublishedContext() const
{
    return d_context;
}

//=============================================================================
//                              MAIN PROGRAM
//-----------------------------------------------------------------------------

int main(int argc, char *argv[])
{
    int test = argc > 1 ? atoi(argv[1]) : 0;
    int verbose = argc > 2;
    //     int veryVerbose = argc > 3; // unused
    int veryVeryVerbose = argc > 4;

    cout << "TEST " << __FILE__ << " CASE " << test << endl;;

    bslma::TestAllocator testAllocator(veryVeryVerbose);

    switch (test) { case 0:  // Zero is always the leading case.
      case 6: {
        // --------------------------------------------------------------------
        // TESTING USAGE EXAMPLE
        //
        // Concerns:
        //   The usage example provided in the component header file must
        //   compile, link, and run on all platforms as shown.
        //
        // Plan:
        //   Incorporate usage example from header into driver, remove leading
        //   comment characters, and replace 'assert' with 'ASSERT'.
        //
        // Testing:
        //   USAGE EXAMPLE
        // --------------------------------------------------------------------

        if (verbose) cout << endl << "Testing Usage Example" << endl
                                  << "=====================" << endl;

        {
            typedef ball::DefaultObserver my_LogfileObserver;
            typedef ball::DefaultObserver my_EncryptingObserver;

            ball::MultiplexObserver multiplexor;
            ASSERT(0 == multiplexor.numRegisteredObservers());

            ball::DefaultObserver  defaultObserver(&bsl::cout);
            my_LogfileObserver     logfileObserver(&bsl::cout);
            my_EncryptingObserver  encryptingObserver(&bsl::cout);

            ASSERT(0 == multiplexor.registerObserver(&defaultObserver));
            ASSERT(0 == multiplexor.registerObserver(&logfileObserver));
            ASSERT(0 == multiplexor.registerObserver(&encryptingObserver));
            ASSERT(3 == multiplexor.numRegisteredObservers());

            // Do *not* do this.  It significantly increases the level # of
            // this component.
            //
            // ball::LoggerManager::initSingleton(&multiplexor);

            ASSERT(0 == multiplexor.deregisterObserver(&defaultObserver));
            ASSERT(0 == multiplexor.deregisterObserver(&logfileObserver));
            ASSERT(0 == multiplexor.deregisterObserver(&encryptingObserver));
            ASSERT(0 == multiplexor.numRegisteredObservers());
        }
      } break;
      case 5: {
        // --------------------------------------------------------------------
        // TESTING ASYNCHRONOUS PUBLISH AND RELEASE RECORDS
        //
        // Concerns:
        //
        //   The primary concerns are:
        //   a. the async publish method
        //      'publish(const bsl::shared_ptr<const ball::Record>&,
        //               const ball::Context&)'
        //      correctly forwards records and their corresponding publication
        //      contexts to all registered observers that should received them.
        //   b. the 'clear' method correctly calls the 'clear' method of all
        //      registered observers.
        //
        // Plan:
        //   Construct a pair of multiplex observers x and y, and a trio of
        //   'TestAsyncObserver' o1, o2, and o3.  Arrange x, y, o1, o2, and o3
        //   into various configurations with o1, o2, and o3 registered with at
        //   most one of the multiplex observers.  Also register y with x for a
        //   portion of the test.  Publish several distinct records to x and
        //   y and verify that all registered observers correctly receive the
        //   records and corresponding publication contexts.  Invoke 'clear'
        //   method of x and y and verify that all registered observers
        //   correctly have their 'clear' methods called.  The helper functions
        //   'nextRecord', 'isNthRecord', and 'isNthContext' are used to
        //   verify that the records and contexts are properly transmitted.
        //
        // Testing:
        //   void publish(const bsl::shared_ptr<const ball::Record>& rec,
        //                const ball::Context&                       ctxt);
        //   void releaseRecords();
        // --------------------------------------------------------------------

        if (verbose) cout << endl << "Testing asynchronous 'publish'" << endl
                                  << "==============================" << endl;

        {
            TestAsyncObserver mO1(bsl::cout);
            const TestAsyncObserver& O1 = mO1;

            TestAsyncObserver mO2(bsl::cout);
            const TestAsyncObserver& O2 = mO2;

            TestAsyncObserver mO3(bsl::cout);
            const TestAsyncObserver& O3 = mO3;

            //  X
            Obj mX;  const Obj& X = mX;
            ASSERT(0 == X.numRegisteredObservers());

            //  Y
            Obj mY;  const Obj& Y = mY;
            ASSERT(0 == Y.numRegisteredObservers());

            bsl::shared_ptr<ball::Record> mR(
                              new (testAllocator) ball::Record(&testAllocator),
                              &testAllocator);
            const bsl::shared_ptr<ball::Record>& R = mR;

            Ctxt mC(ball::Transmission::e_TRIGGER, 0, SEQUENCE_LENGTH);
            const Ctxt& C = mC;

            //   X
            //   |
            //   O1
            ASSERT(0 == mX.registerObserver(&mO1));
            ASSERT(1 == X.numRegisteredObservers());
            ASSERT(0 == O1.numPublishedRecords());

            const int I1 = nextRecord(*mR);  ASSERT(1 == isNthRecord(*R, I1));
            mC.setRecordIndexRaw(I1);        ASSERT(1 == isNthContext(C, I1));
            mX.publish(R, C);
            mX.releaseRecords();
            ASSERT(1 == O1.numPublishedRecords());
            ASSERT(1 == O1.numClears());
            ASSERT(1 == isNthRecord(O1.lastPublishedRecord(), I1));
            ASSERT(1 == isNthContext(O1.lastPublishedContext(), I1));

            //   X
            ASSERT(0 == mX.deregisterObserver(&mO1));
            ASSERT(0 == X.numRegisteredObservers());

            const int I2 = nextRecord(*mR);  ASSERT(1 == isNthRecord(*R, I2));
            mC.setRecordIndexRaw(I2);        ASSERT(1 == isNthContext(C, I2));
            mX.publish(R, C);
            mX.releaseRecords();
            ASSERT(1 == O1.numPublishedRecords());
            ASSERT(2 == O1.numClears());
            ASSERT(1 == isNthRecord(O1.lastPublishedRecord(), I1));
            ASSERT(1 == isNthContext(O1.lastPublishedContext(), I1));

            //   X
            //   |
            //   O1
            ASSERT(0 == mX.registerObserver(&mO1));
            ASSERT(1 == X.numRegisteredObservers());
            ASSERT(1 == O1.numPublishedRecords());

            const int I3 = nextRecord(*mR);  ASSERT(1 == isNthRecord(*R, I3));
            mC.setRecordIndexRaw(I3);        ASSERT(1 == isNthContext(C, I3));
            mX.publish(R, C);
            mX.releaseRecords();
            ASSERT(2 == O1.numPublishedRecords());
            ASSERT(3 == O1.numClears());
            ASSERT(1 == isNthRecord(O1.lastPublishedRecord(), I3));
            ASSERT(1 == isNthContext(O1.lastPublishedContext(), I3));

            //     X
            //    / |
            //  O1  O2
            ASSERT(0 == mX.registerObserver(&mO2));
            ASSERT(2 == X.numRegisteredObservers());
            ASSERT(0 == O2.numPublishedRecords());

            const int I4 = nextRecord(*mR);  ASSERT(1 == isNthRecord(*R, I4));
            mC.setRecordIndexRaw(I4);        ASSERT(1 == isNthContext(C, I4));
            mX.publish(R, C);
            mX.releaseRecords();
            ASSERT(3 == O1.numPublishedRecords());
            ASSERT(4 == O1.numClears());
            ASSERT(1 == isNthRecord(O1.lastPublishedRecord(), I4));
            ASSERT(1 == isNthContext(O1.lastPublishedContext(), I4));
            ASSERT(1 == O2.numPublishedRecords());
            ASSERT(1 == O2.numClears());
            ASSERT(1 == isNthRecord(O2.lastPublishedRecord(), I4));
            ASSERT(1 == isNthContext(O2.lastPublishedContext(), I4));

            //     --X--
            //    /  |  |
            //  O1   O2 Y
            ASSERT(0 == mX.registerObserver(&mY));
            ASSERT(3 == X.numRegisteredObservers());
            ASSERT(0 == Y.numRegisteredObservers());

            const int I5 = nextRecord(*mR);  ASSERT(1 == isNthRecord(*R, I5));
            mC.setRecordIndexRaw(I5);        ASSERT(1 == isNthContext(C, I5));
            mX.publish(R, C);
            mX.releaseRecords();
            ASSERT(4 == O1.numPublishedRecords());
            ASSERT(5 == O1.numClears());
            ASSERT(1 == isNthRecord(O1.lastPublishedRecord(), I5));
            ASSERT(1 == isNthContext(O1.lastPublishedContext(), I5));
            ASSERT(2 == O2.numPublishedRecords());
            ASSERT(2 == O2.numClears());
            ASSERT(1 == isNthRecord(O2.lastPublishedRecord(), I5));
            ASSERT(1 == isNthContext(O2.lastPublishedContext(), I5));

            //     --X--
            //    /  |  |
            //  O1   O2 Y
            //          |
            //          O3
            ASSERT(0 == mY.registerObserver(&mO3));
            ASSERT(3 == X.numRegisteredObservers());
            ASSERT(1 == Y.numRegisteredObservers());
            ASSERT(0 == O3.numPublishedRecords());

            const int I6 = nextRecord(*mR);  ASSERT(1 == isNthRecord(*R, I6));
            mC.setRecordIndexRaw(I6);        ASSERT(1 == isNthContext(C, I6));
            mX.publish(R, C);
            mX.releaseRecords();
            ASSERT(5 == O1.numPublishedRecords());
            ASSERT(6 == O1.numClears());
            ASSERT(1 == isNthRecord(O1.lastPublishedRecord(), I6));
            ASSERT(1 == isNthContext(O1.lastPublishedContext(), I6));
            ASSERT(3 == O2.numPublishedRecords());
            ASSERT(3 == O2.numClears());
            ASSERT(1 == isNthRecord(O2.lastPublishedRecord(), I6));
            ASSERT(1 == isNthContext(O2.lastPublishedContext(), I6));
            ASSERT(1 == O3.numPublishedRecords());
            ASSERT(1 == O3.numClears());
            ASSERT(1 == isNthRecord(O3.lastPublishedRecord(), I6));
            ASSERT(1 == isNthContext(O3.lastPublishedContext(), I6));

            //     X
            //    / |
            //  O1  Y
            //      |
            //      O3
            ASSERT(0 == mX.deregisterObserver(&mO2));
            ASSERT(2 == X.numRegisteredObservers());
            ASSERT(1 == Y.numRegisteredObservers());

            const int I7 = nextRecord(*mR);  ASSERT(1 == isNthRecord(*R, I7));
            mC.setRecordIndexRaw(I7);        ASSERT(1 == isNthContext(C, I7));
            mX.publish(R, C);
            mX.releaseRecords();
            ASSERT(6 == O1.numPublishedRecords());
            ASSERT(7 == O1.numClears());
            ASSERT(1 == isNthRecord(O1.lastPublishedRecord(), I7));
            ASSERT(1 == isNthContext(O1.lastPublishedContext(), I7));
            ASSERT(3 == O2.numPublishedRecords());
            ASSERT(4 == O2.numClears());
            ASSERT(1 == isNthRecord(O2.lastPublishedRecord(), I6));
            ASSERT(1 == isNthContext(O2.lastPublishedContext(), I6));
            ASSERT(2 == O3.numPublishedRecords());
            ASSERT(2 == O3.numClears());
            ASSERT(1 == isNthRecord(O3.lastPublishedRecord(), I7));
            ASSERT(1 == isNthContext(O3.lastPublishedContext(), I7));

            //     X
            //    / |
            //  O1  Y
            //     / |
            //   O3  O2
            ASSERT(0 == mY.registerObserver(&mO2));
            ASSERT(2 == X.numRegisteredObservers());
            ASSERT(2 == Y.numRegisteredObservers());
            ASSERT(3 == O2.numPublishedRecords());

            const int I8 = nextRecord(*mR);  ASSERT(1 == isNthRecord(*R, I8));
            mC.setRecordIndexRaw(I8);        ASSERT(1 == isNthContext(C, I8));
            mX.publish(R, C);
            mX.releaseRecords();
            ASSERT(7 == O1.numPublishedRecords());
            ASSERT(8 == O1.numClears());
            ASSERT(1 == isNthRecord(O1.lastPublishedRecord(), I8));
            ASSERT(1 == isNthContext(O1.lastPublishedContext(), I8));
            ASSERT(4 == O2.numPublishedRecords());
            ASSERT(5 == O2.numClears());
            ASSERT(1 == isNthRecord(O2.lastPublishedRecord(), I8));
            ASSERT(1 == isNthContext(O2.lastPublishedContext(), I8));
            ASSERT(3 == O3.numPublishedRecords());
            ASSERT(3 == O3.numClears());
            ASSERT(1 == isNthRecord(O3.lastPublishedRecord(), I8));
            ASSERT(1 == isNthContext(O3.lastPublishedContext(), I8));

            //     X
            //    / |
            //  O1  Y
            //      |
            //      O2
            ASSERT(0 == mY.deregisterObserver(&mO3));
            ASSERT(2 == X.numRegisteredObservers());
            ASSERT(1 == Y.numRegisteredObservers());

            const int I9 = nextRecord(*mR);  ASSERT(1 == isNthRecord(*R, I9));
            mC.setRecordIndexRaw(I9);        ASSERT(1 == isNthContext(C, I9));
            mX.publish(R, C);
            mX.releaseRecords();
            ASSERT(8 == O1.numPublishedRecords());
            ASSERT(9 == O1.numClears());
            ASSERT(1 == isNthRecord(O1.lastPublishedRecord(), I9));
            ASSERT(1 == isNthContext(O1.lastPublishedContext(), I9));
            ASSERT(5 == O2.numPublishedRecords());
            ASSERT(6 == O2.numClears());
            ASSERT(1 == isNthRecord(O2.lastPublishedRecord(), I9));
            ASSERT(1 == isNthContext(O2.lastPublishedContext(), I9));
            ASSERT(3 == O3.numPublishedRecords());
            ASSERT(4 == O3.numClears());
            ASSERT(1 == isNthRecord(O3.lastPublishedRecord(), I8));
            ASSERT(1 == isNthContext(O3.lastPublishedContext(), I8));

            //   X   Y
            //   |   |
            //   O1  O2
            ASSERT(0 == mX.deregisterObserver(&mY));
            ASSERT(1 == X.numRegisteredObservers());
            ASSERT(1 == Y.numRegisteredObservers());

            const int I10 = nextRecord(*mR); ASSERT(1 == isNthRecord(*R, I10));
            mC.setRecordIndexRaw(I10);       ASSERT(1 == isNthContext(C, I10));
            mX.publish(R, C);
            mX.releaseRecords();
            ASSERT(9 == O1.numPublishedRecords());
            ASSERT(10 == O1.numClears());
            ASSERT(1 == isNthRecord(O1.lastPublishedRecord(), I10));
            ASSERT(1 == isNthContext(O1.lastPublishedContext(), I10));
            ASSERT(5 == O2.numPublishedRecords());
            ASSERT(7 == O2.numClears());
            ASSERT(1 == isNthRecord(O2.lastPublishedRecord(), I9));
            ASSERT(1 == isNthContext(O2.lastPublishedContext(), I9));
            ASSERT(3 == O3.numPublishedRecords());
            ASSERT(4 == O3.numClears());
            ASSERT(1 == isNthRecord(O3.lastPublishedRecord(), I8));
            ASSERT(1 == isNthContext(O3.lastPublishedContext(), I8));

            const int I11 = nextRecord(*mR); ASSERT(1 == isNthRecord(*R, I11));
            mC.setRecordIndexRaw(I11);       ASSERT(1 == isNthContext(C, I11));
            mY.publish(R, C);
            mY.releaseRecords();
            ASSERT(9 == O1.numPublishedRecords());
            ASSERT(10 == O1.numClears());
            ASSERT(1 == isNthRecord(O1.lastPublishedRecord(), I10));
            ASSERT(1 == isNthContext(O1.lastPublishedContext(), I10));
            ASSERT(6 == O2.numPublishedRecords());
            ASSERT(8 == O2.numClears());
            ASSERT(1 == isNthRecord(O2.lastPublishedRecord(), I11));
            ASSERT(1 == isNthContext(O2.lastPublishedContext(), I11));
            ASSERT(3 == O3.numPublishedRecords());
            ASSERT(4 == O3.numClears());
            ASSERT(1 == isNthRecord(O3.lastPublishedRecord(), I8));
            ASSERT(1 == isNthContext(O3.lastPublishedContext(), I8));

            //   X   Y
            //       |
            //       O2
            ASSERT(0 == mX.deregisterObserver(&mO1));
            ASSERT(0 == X.numRegisteredObservers());
            ASSERT(1 == Y.numRegisteredObservers());

            const int I12 = nextRecord(*mR); ASSERT(1 == isNthRecord(*R, I12));
            mC.setRecordIndexRaw(I12);       ASSERT(1 == isNthContext(C, I12));
            mX.publish(R, C);
            mX.releaseRecords();
            ASSERT(9 == O1.numPublishedRecords());
            ASSERT(11 == O1.numClears());
            ASSERT(1 == isNthRecord(O1.lastPublishedRecord(), I10));
            ASSERT(1 == isNthContext(O1.lastPublishedContext(), I10));
            ASSERT(6 == O2.numPublishedRecords());
            ASSERT(8 == O2.numClears());
            ASSERT(1 == isNthRecord(O2.lastPublishedRecord(), I11));
            ASSERT(1 == isNthContext(O2.lastPublishedContext(), I11));
            ASSERT(3 == O3.numPublishedRecords());
            ASSERT(4 == O3.numClears());
            ASSERT(1 == isNthRecord(O3.lastPublishedRecord(), I8));
            ASSERT(1 == isNthContext(O3.lastPublishedContext(), I8));

            const int I13 = nextRecord(*mR); ASSERT(1 == isNthRecord(*R, I13));
            mC.setRecordIndexRaw(I13);       ASSERT(1 == isNthContext(C, I13));
            mY.publish(R, C);
            mY.releaseRecords();
            ASSERT(9 == O1.numPublishedRecords());
            ASSERT(11 == O1.numClears());
            ASSERT(1 == isNthRecord(O1.lastPublishedRecord(), I10));
            ASSERT(1 == isNthContext(O1.lastPublishedContext(), I10));
            ASSERT(7 == O2.numPublishedRecords());
            ASSERT(9 == O2.numClears());
            ASSERT(1 == isNthRecord(O2.lastPublishedRecord(), I13));
            ASSERT(1 == isNthContext(O2.lastPublishedContext(), I13));
            ASSERT(3 == O3.numPublishedRecords());
            ASSERT(4 == O3.numClears());
            ASSERT(1 == isNthRecord(O3.lastPublishedRecord(), I8));
            ASSERT(1 == isNthContext(O3.lastPublishedContext(), I8));

            //   X   Y
            ASSERT(0 == mY.deregisterObserver(&mO2));
            ASSERT(0 == X.numRegisteredObservers());
            ASSERT(0 == Y.numRegisteredObservers());

            const int I14 = nextRecord(*mR); ASSERT(1 == isNthRecord(*R, I14));
            mC.setRecordIndexRaw(I14);       ASSERT(1 == isNthContext(C, I14));
            mX.publish(R, C);
            mX.releaseRecords();
            mY.publish(R, C);
            mY.releaseRecords();
            ASSERT(9 == O1.numPublishedRecords());
            ASSERT(11 == O1.numClears());
            ASSERT(1 == isNthRecord(O1.lastPublishedRecord(), I10));
            ASSERT(1 == isNthContext(O1.lastPublishedContext(), I10));
            ASSERT(7 == O2.numPublishedRecords());
            ASSERT(10 == O2.numClears());
            ASSERT(1 == isNthRecord(O2.lastPublishedRecord(), I13));
            ASSERT(1 == isNthContext(O2.lastPublishedContext(), I13));
            ASSERT(3 == O3.numPublishedRecords());
            ASSERT(4 == O3.numClears());
            ASSERT(1 == isNthRecord(O3.lastPublishedRecord(), I8));
            ASSERT(1 == isNthContext(O3.lastPublishedContext(), I8));
        }
      } break;
      case 4: {
        // --------------------------------------------------------------------
        // TESTING SYNCHRONOUS (DEPRECATED) PUBLISH
        //
        // Concerns:
        //   The primary concern is that the sync publish method
        //   'publish(const ball::Record&, const ball::Context&)' correctly
        //   forwards records and their corresponding publication contexts
        //   to all registered observers that should received them.
        //
        // Plan:
        //   Construct a pair of multiplex observers x and y, and a trio of
        //   test observers o1, o2, and o3.  Arrange x, y, o1, o2, and o3 into
        //   various configurations with o1, o2, and o3 registered with at most
        //   one of the multiplex observers.  Also register y with x for a
        //   portion of the test.  Publish several distinct records to x and
        //   y and verify that all registered observers correctly receive the
        //   records and corresponding publication contexts.  The helper
        //   functions 'nextRecord', 'isNthRecord', and 'isNthContext' are
        //   used to verify that the records and contexts are properly
        //   transmitted.
        //
        // Testing:
        //   void publish(const ball::Record& rec, const ball::Context& ctxt);
        // --------------------------------------------------------------------

        if (verbose) cout << endl << "Testing synchronous 'publish'" << endl
                                  << "=============================" << endl;

        {
            TestObs mO1(bsl::cout);  const TestObs& O1 = mO1;
            TestObs mO2(bsl::cout);  const TestObs& O2 = mO2;
            TestObs mO3(bsl::cout);  const TestObs& O3 = mO3;

            //  X
            Obj mX;  const Obj& X = mX;
            ASSERT(0 == X.numRegisteredObservers());

            //  Y
            Obj mY;  const Obj& Y = mY;
            ASSERT(0 == Y.numRegisteredObservers());

            Rec mR;  const Rec& R = mR;

            Ctxt mC(ball::Transmission::e_TRIGGER, 0, SEQUENCE_LENGTH);
            const Ctxt& C = mC;

            //   X
            //   |
            //   O1
            ASSERT(0 == mX.registerObserver(&mO1));
            ASSERT(1 == X.numRegisteredObservers());
            ASSERT(0 == O1.numPublishedRecords());

            const int I1 = nextRecord(mR);  ASSERT(1 == isNthRecord(R, I1));
            mC.setRecordIndexRaw(I1);       ASSERT(1 == isNthContext(C, I1));
            mX.publish(R, C);
            ASSERT(1 == O1.numPublishedRecords());
            ASSERT(1 == isNthRecord(O1.lastPublishedRecord(), I1));
            ASSERT(1 == isNthContext(O1.lastPublishedContext(), I1));

            //   X
            ASSERT(0 == mX.deregisterObserver(&mO1));
            ASSERT(0 == X.numRegisteredObservers());

            const int I2 = nextRecord(mR);  ASSERT(1 == isNthRecord(R, I2));
            mC.setRecordIndexRaw(I2);       ASSERT(1 == isNthContext(C, I2));
            mX.publish(R, C);
            ASSERT(1 == O1.numPublishedRecords());
            ASSERT(1 == isNthRecord(O1.lastPublishedRecord(), I1));
            ASSERT(1 == isNthContext(O1.lastPublishedContext(), I1));

            //   X
            //   |
            //   O1
            ASSERT(0 == mX.registerObserver(&mO1));
            ASSERT(1 == X.numRegisteredObservers());
            ASSERT(1 == O1.numPublishedRecords());

            const int I3 = nextRecord(mR);  ASSERT(1 == isNthRecord(R, I3));
            mC.setRecordIndexRaw(I3);       ASSERT(1 == isNthContext(C, I3));
            mX.publish(R, C);
            ASSERT(2 == O1.numPublishedRecords());
            ASSERT(1 == isNthRecord(O1.lastPublishedRecord(), I3));
            ASSERT(1 == isNthContext(O1.lastPublishedContext(), I3));

            //     X
            //    / |
            //  O1  O2
            ASSERT(0 == mX.registerObserver(&mO2));
            ASSERT(2 == X.numRegisteredObservers());
            ASSERT(0 == O2.numPublishedRecords());

            const int I4 = nextRecord(mR);  ASSERT(1 == isNthRecord(R, I4));
            mC.setRecordIndexRaw(I4);       ASSERT(1 == isNthContext(C, I4));
            mX.publish(R, C);
            ASSERT(3 == O1.numPublishedRecords());
            ASSERT(1 == isNthRecord(O1.lastPublishedRecord(), I4));
            ASSERT(1 == isNthContext(O1.lastPublishedContext(), I4));
            ASSERT(1 == O2.numPublishedRecords());
            ASSERT(1 == isNthRecord(O2.lastPublishedRecord(), I4));
            ASSERT(1 == isNthContext(O2.lastPublishedContext(), I4));

            //     --X--
            //    /  |  |
            //  O1   O2 Y
            ASSERT(0 == mX.registerObserver(&mY));
            ASSERT(3 == X.numRegisteredObservers());
            ASSERT(0 == Y.numRegisteredObservers());

            const int I5 = nextRecord(mR);  ASSERT(1 == isNthRecord(R, I5));
            mC.setRecordIndexRaw(I5);       ASSERT(1 == isNthContext(C, I5));
            mX.publish(R, C);
            ASSERT(4 == O1.numPublishedRecords());
            ASSERT(1 == isNthRecord(O1.lastPublishedRecord(), I5));
            ASSERT(1 == isNthContext(O1.lastPublishedContext(), I5));
            ASSERT(2 == O2.numPublishedRecords());
            ASSERT(1 == isNthRecord(O2.lastPublishedRecord(), I5));
            ASSERT(1 == isNthContext(O2.lastPublishedContext(), I5));

            //     --X--
            //    /  |  |
            //  O1   O2 Y
            //          |
            //          O3
            ASSERT(0 == mY.registerObserver(&mO3));
            ASSERT(3 == X.numRegisteredObservers());
            ASSERT(1 == Y.numRegisteredObservers());
            ASSERT(0 == O3.numPublishedRecords());

            const int I6 = nextRecord(mR);  ASSERT(1 == isNthRecord(R, I6));
            mC.setRecordIndexRaw(I6);       ASSERT(1 == isNthContext(C, I6));
            mX.publish(R, C);
            ASSERT(5 == O1.numPublishedRecords());
            ASSERT(1 == isNthRecord(O1.lastPublishedRecord(), I6));
            ASSERT(1 == isNthContext(O1.lastPublishedContext(), I6));
            ASSERT(3 == O2.numPublishedRecords());
            ASSERT(1 == isNthRecord(O2.lastPublishedRecord(), I6));
            ASSERT(1 == isNthContext(O2.lastPublishedContext(), I6));
            ASSERT(1 == O3.numPublishedRecords());
            ASSERT(1 == isNthRecord(O3.lastPublishedRecord(), I6));
            ASSERT(1 == isNthContext(O3.lastPublishedContext(), I6));

            //     X
            //    / |
            //  O1  Y
            //      |
            //      O3
            ASSERT(0 == mX.deregisterObserver(&mO2));
            ASSERT(2 == X.numRegisteredObservers());
            ASSERT(1 == Y.numRegisteredObservers());

            const int I7 = nextRecord(mR);  ASSERT(1 == isNthRecord(R, I7));
            mC.setRecordIndexRaw(I7);       ASSERT(1 == isNthContext(C, I7));
            mX.publish(R, C);
            ASSERT(6 == O1.numPublishedRecords());
            ASSERT(1 == isNthRecord(O1.lastPublishedRecord(), I7));
            ASSERT(1 == isNthContext(O1.lastPublishedContext(), I7));
            ASSERT(3 == O2.numPublishedRecords());
            ASSERT(1 == isNthRecord(O2.lastPublishedRecord(), I6));
            ASSERT(1 == isNthContext(O2.lastPublishedContext(), I6));
            ASSERT(2 == O3.numPublishedRecords());
            ASSERT(1 == isNthRecord(O3.lastPublishedRecord(), I7));
            ASSERT(1 == isNthContext(O3.lastPublishedContext(), I7));

            //     X
            //    / |
            //  O1  Y
            //     / |
            //   O3  O2
            ASSERT(0 == mY.registerObserver(&mO2));
            ASSERT(2 == X.numRegisteredObservers());
            ASSERT(2 == Y.numRegisteredObservers());
            ASSERT(3 == O2.numPublishedRecords());

            const int I8 = nextRecord(mR);  ASSERT(1 == isNthRecord(R, I8));
            mC.setRecordIndexRaw(I8);       ASSERT(1 == isNthContext(C, I8));
            mX.publish(R, C);
            ASSERT(7 == O1.numPublishedRecords());
            ASSERT(1 == isNthRecord(O1.lastPublishedRecord(), I8));
            ASSERT(1 == isNthContext(O1.lastPublishedContext(), I8));
            ASSERT(4 == O2.numPublishedRecords());
            ASSERT(1 == isNthRecord(O2.lastPublishedRecord(), I8));
            ASSERT(1 == isNthContext(O2.lastPublishedContext(), I8));
            ASSERT(3 == O3.numPublishedRecords());
            ASSERT(1 == isNthRecord(O3.lastPublishedRecord(), I8));
            ASSERT(1 == isNthContext(O3.lastPublishedContext(), I8));

            //     X
            //    / |
            //  O1  Y
            //      |
            //      O2
            ASSERT(0 == mY.deregisterObserver(&mO3));
            ASSERT(2 == X.numRegisteredObservers());
            ASSERT(1 == Y.numRegisteredObservers());

            const int I9 = nextRecord(mR);  ASSERT(1 == isNthRecord(R, I9));
            mC.setRecordIndexRaw(I9);       ASSERT(1 == isNthContext(C, I9));
            mX.publish(R, C);
            ASSERT(8 == O1.numPublishedRecords());
            ASSERT(1 == isNthRecord(O1.lastPublishedRecord(), I9));
            ASSERT(1 == isNthContext(O1.lastPublishedContext(), I9));
            ASSERT(5 == O2.numPublishedRecords());
            ASSERT(1 == isNthRecord(O2.lastPublishedRecord(), I9));
            ASSERT(1 == isNthContext(O2.lastPublishedContext(), I9));
            ASSERT(3 == O3.numPublishedRecords());
            ASSERT(1 == isNthRecord(O3.lastPublishedRecord(), I8));
            ASSERT(1 == isNthContext(O3.lastPublishedContext(), I8));

            //   X   Y
            //   |   |
            //   O1  O2
            ASSERT(0 == mX.deregisterObserver(&mY));
            ASSERT(1 == X.numRegisteredObservers());
            ASSERT(1 == Y.numRegisteredObservers());

            const int I10 = nextRecord(mR);  ASSERT(1 == isNthRecord(R, I10));
            mC.setRecordIndexRaw(I10);       ASSERT(1 == isNthContext(C, I10));
            mX.publish(R, C);
            ASSERT(9 == O1.numPublishedRecords());
            ASSERT(1 == isNthRecord(O1.lastPublishedRecord(), I10));
            ASSERT(1 == isNthContext(O1.lastPublishedContext(), I10));
            ASSERT(5 == O2.numPublishedRecords());
            ASSERT(1 == isNthRecord(O2.lastPublishedRecord(), I9));
            ASSERT(1 == isNthContext(O2.lastPublishedContext(), I9));
            ASSERT(3 == O3.numPublishedRecords());
            ASSERT(1 == isNthRecord(O3.lastPublishedRecord(), I8));
            ASSERT(1 == isNthContext(O3.lastPublishedContext(), I8));

            const int I11 = nextRecord(mR);  ASSERT(1 == isNthRecord(R, I11));
            mC.setRecordIndexRaw(I11);       ASSERT(1 == isNthContext(C, I11));
            mY.publish(R, C);
            ASSERT(9 == O1.numPublishedRecords());
            ASSERT(1 == isNthRecord(O1.lastPublishedRecord(), I10));
            ASSERT(1 == isNthContext(O1.lastPublishedContext(), I10));
            ASSERT(6 == O2.numPublishedRecords());
            ASSERT(1 == isNthRecord(O2.lastPublishedRecord(), I11));
            ASSERT(1 == isNthContext(O2.lastPublishedContext(), I11));
            ASSERT(3 == O3.numPublishedRecords());
            ASSERT(1 == isNthRecord(O3.lastPublishedRecord(), I8));
            ASSERT(1 == isNthContext(O3.lastPublishedContext(), I8));

            //   X   Y
            //       |
            //       O2
            ASSERT(0 == mX.deregisterObserver(&mO1));
            ASSERT(0 == X.numRegisteredObservers());
            ASSERT(1 == Y.numRegisteredObservers());

            const int I12 = nextRecord(mR);  ASSERT(1 == isNthRecord(R, I12));
            mC.setRecordIndexRaw(I12);       ASSERT(1 == isNthContext(C, I12));
            mX.publish(R, C);
            ASSERT(9 == O1.numPublishedRecords());
            ASSERT(1 == isNthRecord(O1.lastPublishedRecord(), I10));
            ASSERT(1 == isNthContext(O1.lastPublishedContext(), I10));
            ASSERT(6 == O2.numPublishedRecords());
            ASSERT(1 == isNthRecord(O2.lastPublishedRecord(), I11));
            ASSERT(1 == isNthContext(O2.lastPublishedContext(), I11));
            ASSERT(3 == O3.numPublishedRecords());
            ASSERT(1 == isNthRecord(O3.lastPublishedRecord(), I8));
            ASSERT(1 == isNthContext(O3.lastPublishedContext(), I8));

            const int I13 = nextRecord(mR);  ASSERT(1 == isNthRecord(R, I13));
            mC.setRecordIndexRaw(I13);       ASSERT(1 == isNthContext(C, I13));
            mY.publish(R, C);
            ASSERT(9 == O1.numPublishedRecords());
            ASSERT(1 == isNthRecord(O1.lastPublishedRecord(), I10));
            ASSERT(1 == isNthContext(O1.lastPublishedContext(), I10));
            ASSERT(7 == O2.numPublishedRecords());
            ASSERT(1 == isNthRecord(O2.lastPublishedRecord(), I13));
            ASSERT(1 == isNthContext(O2.lastPublishedContext(), I13));
            ASSERT(3 == O3.numPublishedRecords());
            ASSERT(1 == isNthRecord(O3.lastPublishedRecord(), I8));
            ASSERT(1 == isNthContext(O3.lastPublishedContext(), I8));

            //   X   Y
            ASSERT(0 == mY.deregisterObserver(&mO2));
            ASSERT(0 == X.numRegisteredObservers());
            ASSERT(0 == Y.numRegisteredObservers());

            const int I14 = nextRecord(mR);  ASSERT(1 == isNthRecord(R, I14));
            mC.setRecordIndexRaw(I14);       ASSERT(1 == isNthContext(C, I14));
            mX.publish(R, C);
            mY.publish(R, C);
            ASSERT(9 == O1.numPublishedRecords());
            ASSERT(1 == isNthRecord(O1.lastPublishedRecord(), I10));
            ASSERT(1 == isNthContext(O1.lastPublishedContext(), I10));
            ASSERT(7 == O2.numPublishedRecords());
            ASSERT(1 == isNthRecord(O2.lastPublishedRecord(), I13));
            ASSERT(1 == isNthContext(O2.lastPublishedContext(), I13));
            ASSERT(3 == O3.numPublishedRecords());
            ASSERT(1 == isNthRecord(O3.lastPublishedRecord(), I8));
            ASSERT(1 == isNthContext(O3.lastPublishedContext(), I8));
        }
      } break;
      case 3: {
        // --------------------------------------------------------------------
        // TESTING OBSERVER REGISTRATION
        //
        // Concerns:
        //   Our concerns are that 'registerObserver' and 'deregisterObserver'
        //   produce the expected side-effects on the container of observers
        //   and that 'numRegisteredObservers' returns the current number of
        //   registered observers.
        //
        // Plan:
        //   Construct a pair of multiplex observers x and y, and a trio of
        //   test observers o1, o2, and o3.  Arrange x, y, o1, o2, and o3 into
        //   various configurations with o1, o2, and o3 registered with at most
        //   one of the multiplex observers.  Also register y with x for a
        //   portion of the test.  Test the return value of the three methods
        //   under test to infer that they fulfill their contractual
        //   obligations.
        //
        // Testing:
        //   int registerObserver(ball::Observer *observer);
        //   int deregisterObserver(ball::Observer *observer);
        //   int numRegisteredObservers() const;
        // --------------------------------------------------------------------

        if (verbose) cout << endl << "Testing Observer Registration" << endl
                                  << "=============================" << endl;

        if (verbose)
            cout << "Testing invalid registration and deregistration." << endl;
        {
            Obj mX;  const Obj& X = mX;
            ASSERT(0 == X.numRegisteredObservers());

            TestObs mO1(bsl::cout);
            TestObs mO2(bsl::cout);

            ASSERT(0 != mX.registerObserver(0));
            ASSERT(0 == X.numRegisteredObservers());

            ASSERT(0 != mX.deregisterObserver(&mO1));
            ASSERT(0 != mX.deregisterObserver(0));
            ASSERT(0 == X.numRegisteredObservers());

            ASSERT(0 == mX.registerObserver(&mO1));
            ASSERT(1 == X.numRegisteredObservers());

            ASSERT(0 != mX.registerObserver(0));
            ASSERT(0 != mX.registerObserver(&mO1));
            ASSERT(1 == X.numRegisteredObservers());

            ASSERT(0 != mX.deregisterObserver(&mO2));
            ASSERT(0 != mX.deregisterObserver(0));
            ASSERT(1 == X.numRegisteredObservers());

            ASSERT(0 == mX.deregisterObserver(&mO1));
            ASSERT(0 == X.numRegisteredObservers());

            ASSERT(0 != mX.deregisterObserver(&mO1));
            ASSERT(0 != mX.deregisterObserver(0));
            ASSERT(0 == X.numRegisteredObservers());
        }

        if (verbose)
            cout << "Testing valid registration and deregistration." << endl;
        {
            //  X
            Obj mX;  const Obj& X = mX;
            ASSERT(0 == X.numRegisteredObservers());

            //  Y
            Obj mY;  const Obj& Y = mY;
            ASSERT(0 == Y.numRegisteredObservers());

            TestObs mO1(bsl::cout);
            TestObs mO2(bsl::cout);
            TestObs mO3(bsl::cout);

            //   X
            //   |
            //   O1
            ASSERT(0 == mX.registerObserver(&mO1));
            ASSERT(1 == X.numRegisteredObservers());

            //   X
            ASSERT(0 == mX.deregisterObserver(&mO1));
            ASSERT(0 == X.numRegisteredObservers());

            //   X
            //   |
            //   O1
            ASSERT(0 == mX.registerObserver(&mO1));
            ASSERT(1 == X.numRegisteredObservers());

            //     X
            //    / |
            //  O1  O2
            ASSERT(0 == mX.registerObserver(&mO2));
            ASSERT(2 == X.numRegisteredObservers());

            //     --X--
            //    /  |  |
            //  O1   O2 Y
            ASSERT(0 == mX.registerObserver(&mY));
            ASSERT(3 == X.numRegisteredObservers());
            ASSERT(0 == Y.numRegisteredObservers());

            //     --X--
            //    /  |  |
            //  O1   O2 Y
            //          |
            //          O3
            ASSERT(0 == mY.registerObserver(&mO3));
            ASSERT(3 == X.numRegisteredObservers());
            ASSERT(1 == Y.numRegisteredObservers());

            //     X
            //    / |
            //  O1  Y
            //      |
            //      O3
            ASSERT(0 == mX.deregisterObserver(&mO2));
            ASSERT(2 == X.numRegisteredObservers());
            ASSERT(1 == Y.numRegisteredObservers());

            //     X
            //    / |
            //  O1  Y
            //     / |
            //   O3  O2
            ASSERT(0 == mY.registerObserver(&mO2));
            ASSERT(2 == X.numRegisteredObservers());
            ASSERT(2 == Y.numRegisteredObservers());

            //     X
            //    / |
            //  O1   Y
            //       |
            //       O2
            ASSERT(0 == mY.deregisterObserver(&mO3));
            ASSERT(2 == X.numRegisteredObservers());
            ASSERT(1 == Y.numRegisteredObservers());

            //   X   Y
            //   |   |
            //   O1  O2
            ASSERT(0 == mX.deregisterObserver(&mY));
            ASSERT(1 == X.numRegisteredObservers());
            ASSERT(1 == Y.numRegisteredObservers());

            //   X   Y
            //       |
            //       O2
            ASSERT(0 == mX.deregisterObserver(&mO1));
            ASSERT(0 == X.numRegisteredObservers());
            ASSERT(1 == Y.numRegisteredObservers());

            //   X   Y
            ASSERT(0 == mY.deregisterObserver(&mO2));
            ASSERT(0 == X.numRegisteredObservers());
            ASSERT(0 == Y.numRegisteredObservers());
        }
      } break;
      case 2: {
        // --------------------------------------------------------------------
        // TESTING CTOR AND DTOR
        //
        // Concerns:
        //   The basic concern is that the constructor and destructor operate
        //   as expected.  We have the following specific concerns:
        //     1. The constructor:
        //        a. Creates the correct initial state (empty).
        //        b. Has the internal memory management system hooked up
        //           properly so that *all* internally allocated memory draws
        //           from the same user-supplied allocator whenever one is
        //           specified.
        //     2. The destructor properly deallocates all allocated memory to
        //        its corresponding allocator.
        //
        // Plan:
        //   To address concerns 1a & 1b, create an object:
        //     - With and without passing in an allocator to the constructor.
        //     - Where the object is constructed entirely in static memory
        //       (using a 'bdlma::BufferedSequentialAllocator') and never
        //       destroyed.
        //
        //   To address concern 2, allow each object to leave scope, so that
        //   the destructor asserts internal object invariants appropriately.
        //   Use a 'bslma::TestAllocator' to verify memory usage.
        //
        // Testing:
        //   ball::MultiplexObserver(bslma::Allocator *ba = 0);
        //   ~ball::MultiplexObserver();
        // --------------------------------------------------------------------

        if (verbose) cout << endl << "Testing 'ctor' and 'dtor'" << endl
                                  << "=========================" << endl;

        if (verbose) cout << "\tWithout passing in an allocator." << endl;
        {
            Obj mX;  const Obj& X = mX;
            ASSERT(0 == X.numRegisteredObservers());
        }
        {
            TestObs mO1(bsl::cout);
            TestObs mO2(bsl::cout);

            Obj mX;  const Obj& X = mX;
            ASSERT(0 == X.numRegisteredObservers());

            ASSERT(0 == mX.registerObserver(&mO1));
            ASSERT(0 == mX.registerObserver(&mO2));
            ASSERT(2 == X.numRegisteredObservers());
        }

        if (verbose) cout << "\tPassing in an allocator." << endl;
        const bsls::Types::Int64 NUM_BLOCKS_IN_USE =
                                                testAllocator.numBlocksInUse();
        const bsls::Types::Int64 NUM_BYTES_IN_USE  =
                                                 testAllocator.numBytesInUse();
        {
            Obj mX(&testAllocator);  const Obj& X = mX;
            ASSERT(0 == X.numRegisteredObservers());
        }
        ASSERT(NUM_BLOCKS_IN_USE == testAllocator.numBlocksInUse());
        ASSERT(NUM_BYTES_IN_USE  == testAllocator.numBytesInUse());

        {
            TestObs mO1(bsl::cout);
            TestObs mO2(bsl::cout);

            Obj mX(&testAllocator);  const Obj& X = mX;
            ASSERT(0 == X.numRegisteredObservers());

            ASSERT(0 == mX.registerObserver(&mO1));
            ASSERT(0 == mX.registerObserver(&mO2));
            ASSERT(2 == X.numRegisteredObservers());

            // White-box test: 'publish' does not utilize the supplied
            // allocator.

            const bsls::Types::Int64 NUM_BLOCKS_TOTAL =
                                                testAllocator.numBlocksTotal();
            const bsls::Types::Int64 NUM_BYTES_TOTAL  =
                                                 testAllocator.numBytesTotal();
            Rec  mR;  const Rec&  R = mR;
            Ctxt mC;  const Ctxt& C = mC;
            mX.publish(R, C);
            ASSERT(NUM_BLOCKS_TOTAL == testAllocator.numBlocksTotal());
            ASSERT(NUM_BYTES_TOTAL  == testAllocator.numBytesTotal());
        }
        ASSERT(NUM_BLOCKS_IN_USE == testAllocator.numBlocksInUse());
        ASSERT(NUM_BYTES_IN_USE  == testAllocator.numBytesInUse());

        if (verbose) cout << "\tIn place using a buffer allocator." << endl;
        {
            TestObs mO1(bsl::cout);
            TestObs mO2(bsl::cout);

            char memory[2048];
            bdlma::BufferedSequentialAllocator a(memory, sizeof memory);
            Obj *doNotDelete = new(a.allocate(sizeof(Obj))) Obj(&a);
            Obj& mX = *doNotDelete;  const Obj& X = mX;
            ASSERT(0 == X.numRegisteredObservers());

            ASSERT(0 == mX.registerObserver(&mO1));
            ASSERT(0 == mX.registerObserver(&mO2));
            ASSERT(2 == X.numRegisteredObservers());

            // No destructor is called; will produce memory leak in purify if
            // internal allocators are not hooked up properly.
        }
      } break;
      case 1: {
        // --------------------------------------------------------------------
        // BREATHING TEST
        //
        // Concerns:
        //   We want to exercise basic functionality.  In particular, we want
        //   to demonstrate a base-line level of correct operation for all
        //   methods.
        //
        // Plan:
        //   1.  Construct an object x.
        //   2.  Register an observer o1.
        //   3.  Deregister observer o1.
        //   4.  Reregister observer o1.
        //   4a. Publish a record r1.
        //   5.  Register an observer o2.
        //   5a. Publish a record r2.
        //   6.  Deregister observer o1.
        //   6a. Publish a record r3.
        //   7.  Deregister observer o2.
        //   7a. Publish a record r4.
        //   8.  Destroy x.
        //
        // Testing:
        //   This "test" *exercises* basic functionality, but *tests* nothing.
        // --------------------------------------------------------------------

        if (verbose) cout << endl << "BREATHING TEST" << endl
                                  << "==============" << endl;
        {
            // ----------------------------------------------------------------

            if (verbose) cout << "\t1.  Construct an object x." << endl;

            Obj mX;  const Obj& X = mX;
            ASSERT(0 == X.numRegisteredObservers());

            // ----------------------------------------------------------------

            if (verbose) cout << "\t2.  Register an observer o1." << endl;

            TestObs mO1(bsl::cout);  const TestObs& O1 = mO1;
            ASSERT(0 == mX.registerObserver(&mO1));
            ASSERT(1 == X.numRegisteredObservers());

            // ----------------------------------------------------------------

            if (verbose) cout << "\t3.  Deregister observer o1." << endl;

            ASSERT(0 == mX.deregisterObserver(&mO1));
            ASSERT(0 == X.numRegisteredObservers());

            // ----------------------------------------------------------------

            if (verbose) cout << "\t4.  Reregister observer o1." << endl;

            ASSERT(0 == mX.registerObserver(&mO1));
            ASSERT(1 == X.numRegisteredObservers());
            ASSERT(0 == O1.numPublishedRecords());

            if (verbose) cout << "\t4a. Publish a record r1." << endl;

            Rec  mR1;  const Rec&  R1 = mR1;
            Ctxt mC1;  const Ctxt& C1 = mC1;

            mX.publish(R1, C1);
            ASSERT(1 == O1.numPublishedRecords());

            // ----------------------------------------------------------------

            if (verbose) cout << "\t5.  Register an observer o2." << endl;

            TestObs mO2(bsl::cout);  const TestObs& O2 = mO2;
            ASSERT(0 == mX.registerObserver(&mO2));
            ASSERT(2 == X.numRegisteredObservers());
            ASSERT(0 == O2.numPublishedRecords());

            if (verbose) cout << "\t5a. Publish a record r2." << endl;

            Rec  mR2;  const Rec&  R2 = mR2;
            Ctxt mC2;  const Ctxt& C2 = mC2;

            mX.publish(R2, C2);
            ASSERT(2 == O1.numPublishedRecords());
            ASSERT(1 == O2.numPublishedRecords());

            // ----------------------------------------------------------------

            if (verbose) cout << "\t6.  Deregister observer o1." << endl;

            ASSERT(0 == mX.deregisterObserver(&mO1));
            ASSERT(1 == X.numRegisteredObservers());

            if (verbose) cout << "\t6a. Publish a record r3." << endl;

            Rec  mR3;  const Rec&  R3 = mR3;
            Ctxt mC3;  const Ctxt& C3 = mC3;

            mX.publish(R3, C3);
            ASSERT(2 == O1.numPublishedRecords());
            ASSERT(2 == O2.numPublishedRecords());

            // ----------------------------------------------------------------

            if (verbose) cout << "\t7.  Deregister observer o2." << endl;

            ASSERT(0 == mX.deregisterObserver(&mO2));
            ASSERT(0 == X.numRegisteredObservers());

            if (verbose) cout << "\t7a. Publish a record r4." << endl;

            Rec  mR4;  const Rec&  R4 = mR4;
            Ctxt mC4;  const Ctxt& C4 = mC4;

            mX.publish(R4, C4);
            ASSERT(2 == O1.numPublishedRecords());
            ASSERT(2 == O2.numPublishedRecords());

            // ----------------------------------------------------------------

            if (verbose) cout << "\t8.  Destroy x." << endl;
        }
      } break;
      case -1: {
        // --------------------------------------------------------------------
        // TESTING: Warning about destroyed observer.
        //
        // Concerns:
        //  1 Verify that we log a message to 'stderr' if a registered
        //    observer is destroyed before the multiplex observer is destroyed.
        //
        //  2 Verify that we log a message to 'stderr' if a registered
        //    observer is destroyed before a call to 'releaseRecords'.
        //
        // Plan:
        //  1 Create an observer, and supply it multiplex observer, then
        //    destroy the observer prior to calling 'releaseRecords' and the
        //    destructor of the multiplex observer.  Visually verify that
        //    output is written to stderr.
        //
        //  Note that this is a test of undefined behavior and must be run,
        //  and verified, manually.
        // --------------------------------------------------------------------

        if (verbose) cout << endl
                          << "Warning about destroyed observer." << endl
                          << "================================" << endl;

        {
            Obj x;
            {
                ball::TestObserver testObserver(cout);
                x.registerObserver(&testObserver);
            }
            x.releaseRecords();
        }

      } break;

      default: {
        cerr << "WARNING: CASE `" << test << "' NOT FOUND." << endl;
        testStatus = -1;
      }
    }

    if (testStatus > 0) {
        cerr << "Error, non-zero test status = " << testStatus << "." << endl;
    }
    return testStatus;
}

// ----------------------------------------------------------------------------
// Copyright 2015 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------- END-OF-FILE ----------------------------------


text:
'use strict';

const constants = {
    MODE_CREATE_ELLIPSES: 'createEllipses',
    MODE_CREATE_RECTANGLES: 'createRectangles',
    MODE_SELECT_SHAPES: 'selectShapes',

    EVENT_MOUSEENTER_HANDLE: 'mousenterHandle',
    EVENT_MOUSELEAVE_HANDLE: 'mouseleaveHandle'
};

Object.freeze(constants);

module.exports = constants;

redpajama_set_name: RedPajamaGithub


text:
package main

import (
	"bytes"
	"fmt"
	"io"
	"log"
	"mime/multipart"
	"net/http"
	"net/http/httputil"
	"os"
	"path/filepath"
)

type FileField struct {
	FileName string
	Body     io.Reader
}

func NewUploadRequest(url string, files map[string]FileField, params map[string]string) (*http.Request, error) {
	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	for key, val := range params {
		writer.WriteField(key, val)
	}
	for key, field := range files {
		part, _ := writer.CreateFormFile(key, field.FileName)
		io.Copy(part, field.Body)
	}
	writer.Close()

	req, err := http.NewRequest("POST", url, body)
	if err != nil {
		return nil, err
	}
	req.Header.Add("Content-Type", "multipart/form-data; boundary="+writer.Boundary())
	return req, nil
}

func Upload(url, file string) {
	fio, err := os.Open(file)
	if err != nil {
		log.Fatalln(err)
	}
	defer fio.Close()
	filename := filepath.Base(file)
	field := FileField{
		FileName: filename,
		Body:     fio,
	}
	files := map[string]FileField{
		"file": field,
	}
	req, err := NewUploadRequest(url, files, nil)
	if err != nil {
		log.Println(err)
	}
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Fatalln(err)
	}
	data, err := httputil.DumpResponse(resp, true)
	if err != nil {
		log.Fatalln(err)
	}
	fmt.Print(string(data))
	resp.Body.Close()
}

func main() {
	url := "http://localhost/upload.php"
	file := "upload.go"

	Upload(url, file)
}


text:
#include "tensorflow/compiler/tf2xla/lib/scatter.h"
#include "tensorflow/compiler/tf2xla/type_util.h"
#include "tensorflow/compiler/tf2xla/xla_helpers.h"
#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/xla/client/lib/constants.h"
#include "tensorflow/compiler/xla/client/xla_client/xla_builder.h"

namespace tensorflow {
namespace {

class UnsortedSegmentReduce : public XlaOpKernel {
 public:
  explicit UnsortedSegmentReduce(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {
    DataType dtype;
    OP_REQUIRES_OK(ctx, ctx->GetAttr("T", &dtype));
    OP_REQUIRES_OK(ctx, DataTypeToPrimitiveType(dtype, &type_));
  }

  // The initial value to initialize elements of the output to.
  virtual xla::XlaOp InitialValue(xla::XlaBuilder* builder) = 0;

  // A function to combine two scalars with the same index (e.g., sum).
  virtual xla::XlaOp Combine(xla::XlaOp a, xla::XlaOp b) = 0;

  void Compile(XlaOpKernelContext* ctx) override {
    // output = unsorted_segment_sum(data, indices, num_segments)
    // Compute a tensor such that:
    //    output[i] = sum over {j where indices[j] == i} of data[j]
    //    output[i] == 0 if i does not appear in indices
    //
    // Contrast with segment_sum(), which assumes indices are sorted and that
    // max(indices)+1 is the desired size of the output.
    //
    // The returned output tensor has the same type as data, and the same shape
    // as data with the first indices.rank dimensions are replaced
    // by a single dimension with size num_segments.
    auto data = ctx->Input(0);
    TensorShape data_shape = ctx->InputShape(0);

    auto indices = ctx->Input(1);
    TensorShape indices_shape = ctx->InputShape(1);

    int64 num_segments;
    OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntScalar(2, &num_segments));

    OP_REQUIRES(ctx, data_shape.dims() >= indices_shape.dims(),
                errors::InvalidArgument(type_string(),
                                        " requires that indices' rank be"
                                        " less than or equal to data's rank."));
    // Validate that indices.shape is a prefix of data.shape.
    for (int d = 0; d < indices_shape.dims(); ++d) {
      OP_REQUIRES(
          ctx, (data_shape.dim_size(d) == indices_shape.dim_size(d)),
          errors::InvalidArgument(type_string(),
                                  " requires indices shape to be prefix"
                                  " of data_shape, but dimension ",
                                  d, " differs ", data_shape.dim_size(d),
                                  " vs. ", indices_shape.dim_size(d)));
    }
    xla::XlaBuilder* builder = ctx->builder();
    TensorShape buffer_shape = data_shape;
    buffer_shape.RemoveDimRange(0, indices_shape.dims());
    buffer_shape.InsertDim(0, num_segments);
    auto buffer =
        xla::Broadcast(InitialValue(builder), buffer_shape.dim_sizes());

    auto combiner = [this](xla::XlaOp a, xla::XlaOp b,
                           xla::XlaBuilder* builder) { return Combine(a, b); };

    auto result = XlaScatter(buffer, /*updates=*/data, indices,
                             /*indices_are_vectors=*/false, combiner, builder);
    OP_REQUIRES_OK(ctx, result.status());
    ctx->SetOutput(0, result.ValueOrDie());
  }

 protected:
  xla::PrimitiveType type_;
};

class UnsortedSegmentSum : public UnsortedSegmentReduce {
 public:
  explicit UnsortedSegmentSum(OpKernelConstruction* ctx)
      : UnsortedSegmentReduce(ctx) {}

  xla::XlaOp InitialValue(xla::XlaBuilder* builder) override {
    return xla::Zero(builder, type_);
  };
  xla::XlaOp Combine(xla::XlaOp a, xla::XlaOp b) override { return a + b; };
};

REGISTER_XLA_OP(
    Name("UnsortedSegmentSum").CompileTimeConstInput("num_segments"),
    UnsortedSegmentSum);

class UnsortedSegmentProd : public UnsortedSegmentReduce {
 public:
  explicit UnsortedSegmentProd(OpKernelConstruction* ctx)
      : UnsortedSegmentReduce(ctx) {}

  xla::XlaOp InitialValue(xla::XlaBuilder* builder) override {
    return xla::One(builder, type_);
  };
  xla::XlaOp Combine(xla::XlaOp a, xla::XlaOp b) override { return a * b; };
};

REGISTER_XLA_OP(
    Name("UnsortedSegmentProd").CompileTimeConstInput("num_segments"),
    UnsortedSegmentProd);

class UnsortedSegmentMin : public UnsortedSegmentReduce {
 public:
  explicit UnsortedSegmentMin(OpKernelConstruction* ctx)
      : UnsortedSegmentReduce(ctx) {}

  xla::XlaOp InitialValue(xla::XlaBuilder* builder) override {
    return xla::MaxFiniteValue(builder, type_);
  };
  xla::XlaOp Combine(xla::XlaOp a, xla::XlaOp b) override {
    return xla::Min(a, b);
  };
};

REGISTER_XLA_OP(
    Name("UnsortedSegmentMin").CompileTimeConstInput("num_segments"),
    UnsortedSegmentMin);

class UnsortedSegmentMax : public UnsortedSegmentReduce {
 public:
  explicit UnsortedSegmentMax(OpKernelConstruction* ctx)
      : UnsortedSegmentReduce(ctx) {}

  xla::XlaOp InitialValue(xla::XlaBuilder* builder) override {
    return xla::MinFiniteValue(builder, type_);
  };
  xla::XlaOp Combine(xla::XlaOp a, xla::XlaOp b) override {
    return xla::Max(a, b);
  };
};

REGISTER_XLA_OP(
    Name("UnsortedSegmentMax").CompileTimeConstInput("num_segments"),
    UnsortedSegmentMax);

}  // namespace
}  // namespace tensorflow


text:
Lateralization of amplitudes
================

This file documents and presents the analysis and code used to produce results relating to the lateralization of amplitude suppression presented in Section 3.6 of the manuscript as well as the plots of Figure 5.

We plot the log of the baseline corrected amplitudes for the low alpha frequency bands (i.e., between 6-9 Hz) which were extracted for each parcel and participant from the main analysis pipeline. Amplitude modulations are then averaged across the entire visual cortex as defined by the morphing with the Yeo parcellation.

Amplitude suppression is different between ipsi and contralateral visual cortex
-------------------------------------------------------------------------------

We first plot the data from cue-onset (0 ms) up to a second after cue-onset. We plot the median value across subjects as well as the 25% and 75% quantile to give an overview of the data variability across participants.

![](lateralization_of_amplitude_suppression_visual_cortex_files/figure-markdown_github-ascii_identifiers/unnamed-chunk-2-1.png)

Statistical testing
-------------------

In order to reduce the number of statistical comparisons, we average values within the 200 ms time-windows used throughout the manuscript. We run a statistical comparison for each time-window and attend condition and correct for multiple comps (6 conditions) using Holms Bonferroni corrections

We notice that for the third time window in attend left condition, the data is very skewed, and in different directions for each condition, violating the assumptions of the wilcoxon paired test. We therefore carry out a simple sign test for all conditions and time-windows in order to have comparable power and p-values across all comparisons.

``` r
visualCortexAmpData_Plot<-ggplot(data=visual_system_amplitude_data_stats ,
                                 aes(x=hemisphere , y=logAmp)) +
  geom_boxplot( aes(color=hemi_type), width=0.25) +
  geom_point(aes(color=hemi_type), shape=1) +
  geom_line(aes(group=subjectNb), linetype=3) +
  scale_colour_brewer( type = "seq", palette = 'Set1', direction = 1, name="") +
  facet_grid(TW_Bin ~ condition) +
  theme_classic() +
  theme(legend.position="bottom") +
  xlab("Hemisphere") +
  ylab("log(Amplitudes)")
visualCortexAmpData_Plot
```

![](lateralization_of_amplitude_suppression_visual_cortex_files/figure-markdown_github-ascii_identifiers/unnamed-chunk-4-1.png)

``` r
# Code own sign-test to have simple to handle outputs
compute_sign_test<-function(x){
  n <-sum((x)!=0)
  T <- sum(x<0)
  S <- n - T
  p_value<-2*min(1-pbinom(T-1,n,0.5),pbinom(T,n,0.5))
  data.frame(n=n,S=S,p_value=p_value)}

# Apply sign-test on difference between Ipsi and Contra
# for each time-window and attend condition
stats_results <- visual_system_amplitude_data_stats %>%
  select(-hemisphere) %>%
  spread(hemi_type,logAmp) %>%
  mutate(diff=Contra-Ipsi) %>%
  group_by(condition,TW_Bin) %>%
  do(compute_sign_test(.$diff))

stats_results<-bind_cols(stats_results,data.frame(p_val_corr=p.adjust(stats_results$p_value, method = "holm")))
# pValue=c(0.0009766, 0.01172, 0.06543,0.01172, 0.2266, 0.0009766 )
#Extract and Correct pValues
# signTestResults<-data.frame(signTestResults$TW_Bin, signTestResults$condition,S,pValue,p.adjust(pValue, method = "holm"))
# names(signTestResults)<-c( 'TW_Bin'  , 'condition',  'S' , 'pValue', 'corrp')
```

| condition    | TW\_Bin     |    n|    S|   p\_value|  p\_val\_corr|
|:-------------|:------------|----:|----:|----------:|-------------:|
| Attend Left  | 400-600 ms  |   11|    0|  0.0009766|     0.0058594|
| Attend Left  | 600-800 ms  |   11|    2|  0.0654297|     0.1308594|
| Attend Left  | 800-1000 ms |   11|    3|  0.2265625|     0.2265625|
| Attend Right | 400-600 ms  |   11|    1|  0.0117188|     0.0468750|
| Attend Right | 600-800 ms  |   11|    1|  0.0117188|     0.0468750|
| Attend Right | 800-1000 ms |   11|    0|  0.0009766|     0.0058594|


text:
require 'deviantart/base'

module DeviantArt
  class User::Whois < Base
    # :method: results
    #

    attr_accessor :results
    point_to_class [:results, :[]], DeviantArt::User
  end
end


text:
#import "SCLineString.h"
#import "SCBoundingBox.h"
#import "SCPoint.h"

@implementation SCLineString

@synthesize points;

- (id)initWithCoordinateArray:(NSArray *)coords crs:(NSInteger)c {
  if (self = [super initWithCoordinateArray:coords crs:c]) {
    NSMutableArray *arr = [[NSMutableArray alloc] init];
    for (NSArray *coord in coords) {
      [arr addObject:[[SCPoint alloc] initWithCoordinateArray:coord
                                                          crs:self.crs]];
    }
    self.points = [[NSArray alloc] initWithArray:arr];
    self.bbox = [[SCBoundingBox alloc] initWithPoints:self.points crs:self.crs];
  }
  return self;
}

- (id)initWithCoordinateArray:(NSArray *)coords {
  return [self initWithCoordinateArray:coords crs:4326];
}

- (SCPoint *)first {
  return self.points.firstObject;
}

- (SCPoint *)last {
  return self.points.lastObject;
}

- (GeometryType)type {
  return LINESTRING;
}

#pragma mark - NSObject

- (NSString *)description {
  NSMutableString *str =
      [[NSMutableString alloc] initWithString:@"LineString["];
  [self.points
      enumerateObjectsUsingBlock:^(SCPoint *point, NSUInteger idx, BOOL *stop) {
        [str appendString:[point description]];
      }];
  [str appendString:@"]"];
  return str;
}

- (BOOL)isContained:(SCBoundingBox *)bbox {
  __block BOOL response = NO;
  [self.points
      enumerateObjectsUsingBlock:^(SCPoint *p, NSUInteger idx, BOOL *stop) {
        if ([bbox pointWithin:p]) {
          response = YES;
          *stop = YES;
        }
      }];
  return response;
}

- (SCSimplePoint *)centroid {
  __block double x = 0;
  __block double y = 0;
  [self.points
      enumerateObjectsUsingBlock:^(SCPoint *p, NSUInteger idx, BOOL *stop) {
        x += p.x;
        y += p.y;
      }];
  return [[SCSimplePoint alloc] initWithX:(x / self.points.count)
                                        Y:(y / self.points.count)];
}

- (NSDictionary *)JSONDict {
  NSMutableDictionary *dict =
      [NSMutableDictionary dictionaryWithDictionary:[super JSONDict]];
  NSDictionary *geometry =
      [NSDictionary dictionaryWithObjects:@[
        @"LineString", [self coordinateArrayAsProj:4326]
      ]
                                  forKeys:@[ @"type", @"coordinates" ]];
  [dict setObject:geometry forKey:@"geometry"];
  return dict;
}

- (NSArray *)coordinateArray {
  return [self coordinateArrayAsProj:self.crs];
}

- (NSArray *)coordinateArrayAsProj:(NSInteger)c {
  return [[self.points.rac_sequence map:^NSArray *(SCPoint *p) {
    return [p coordinateArrayAsProj:c];
  }] array];
}

@end


text:
/* overrides to default admin style */

#container {
    min-height: 100%;
    background-color: lightgrey;
}

a:active,
a:focus {
    outline: none;
}

.sidebar-nav {
    padding: 9px 0;
}

.form-group input[type=text] {
    -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
    -moz-box-sizing: border-box; /* Firefox, other Gecko */
    box-sizing: border-box; /* Opera/IE 8+ */
    /* height: 28px;    Note:  This was overriding default form height of 34px */
}

html, body {
    height: 100%;
}

.form-group select {
    -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
    -moz-box-sizing: border-box; /* Firefox, other Gecko */
    box-sizing: border-box; /* Opera/IE 8+ */
}

.controls > p {
    padding-top: 5px;
}

.selector .selector-filter label {
    display: none;
}

    .navbar {
        background-color: #bec2c6;
        border-bottom: 2px solid black;
    }

.selector h2 {
    font-size: 100%;
    margin: 0;
}

.checkbox {
    padding-bottom: 5px;
}

.checkbox label {
    margin-bottom: -20px;
}

fieldset.collapse {
    height: inherit;
}

.add-row {
    margin-bottom: 20px;
}

legend a:hover {
    text-decoration: none;
}

.wide label {
    width: auto !important;
}

/* change_list actions */
.actions select {
    margin-top: 5px;
}

/* change_list table display */
th.action-checkbox-column {
    width: 1.5em;
    text-align: center;
}

td.action-checkbox {
    text-align: center;
}

.tooltip.in {
    opacity: 1
}

/* Hard to see against black text otherwise */

#result_list {
    clear: both;
    width: 100%;
}

p.quandrantOKtext {
    color: black;
    background-color: lightgray;
}

p.quandrantACTIVEtext {
    color: black;
    background-color: green;
}

p.quandrantWARNtext {
    color: black;
    background-color: yellow;
}

p.quandrantALERTtext {
    color: black;
    background-color: red;
}

.dashboard-buttons{
    margin-top: -10px;
}

    .navbar {
        background-color: #bec2c6;
        border-bottom: 2px solid black;
    }
    .nav-link, .dropdown-toggle {
        font-size: 20px;
    }

    ul.dropdown-menu li {
        font-size: 16px;
    }
    ul.dropdown-menu {
        background-color: #bec2c6;
    }
    .nav-item>a  {
        border-color: #d45500;
        border-bottom-color: transparent;
    }
    .nav-item:first-child {
        border-right: 1px solid #95979B;
    }

    .nav-item.last {
        border-left: 1px solid #95979B;
    }

    .nav-item {
        padding-right: 20px;
        padding-left: 20px;
    }
    ul li {
        list-style: none;
    }

    /*.colMS {*/
        /*margin-right: 0;*/
    /*}*/

    .submit-row a.deletelink {
        height: 35px;
    }

    .results {
        width: 100%;
    }
    #result_list {
        width: 100%;
    }

    h1 {
        font-size: 2.5rem;
        color: black;
        font-family: -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;
    }


text:
"""Created on 23.06.17

.. moduleauthor:: Paweł Pecio

"""
from .base import Diff


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="SlidingMenu">
        <attr name="menuSpadding" format="dimension"></attr>
    </declare-styleable>
</resources>


text:
<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

require_once('Fuel_test_base.php');

class Fuel_navigation_test extends Fuel_test_base {

	public function __construct()
	{
		parent::__construct();
	}

	public function setup()
	{
		parent::setup();
		$this->_login();
	}

	public function test_save_navigation()
	{
		$post = $this->_create_nav_item('test', 'Test');
		$page = $this->load_page('fuel/navigation/create', $post);
		$test = $this->_is_success();
		$expected = TRUE;
		$this->run($test, $expected, 'Test for successful save');
	}

	public function test_fuel_nav()
	{
		$expected = strip_whitespace('

Test

');
		$test = strip_whitespace(fuel_nav());
		$this->run($test, $expected, 'Test for successful fuel_nav() rendering');
	}

	protected function _create_nav_item($location, $label, $parent = 0, $group_id = 1)
	{
		$nav['id'] = NULL;
		$nav['group_id'] = $group_id;
		$nav['location'] = $location; // blank page
		$nav['nav_key'] = $location;
		$nav['label'] = $label;
		$nav['parent_id'] = $parent;
		$nav['precedence'] = NULL;
		$nav['attributes'] = NULL;
		$nav['selected'] = NULL;
		$nav['hidden'] = 'no';
		$nav['published'] = 'yes';
		return $nav;
	}

}


text:
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.db.models import Count

from .apps import spectator_apps

class CreatorManager(models.Manager):
    def by_publications(self):
        """
        The Creators who have been most-read, ordered by number of read
        publications (ignoring if any of those publicatinos have been read
        multiple times.)

        Each Creator will have a `num_publications` attribute.
        """
        if not spectator_apps.is_enabled("reading"):
            raise ImproperlyConfigured(
                "To use the CreatorManager.by_publications() method, "
                "'spectator.reading' must by in INSTALLED_APPS."
            )

        qs = self.get_queryset()

        qs = (
            qs.exclude(publications__reading__isnull=True)
            .exclude(publications__reading__is_finished=False)
            .annotate(num_publications=Count("publications"))
            .order_by("-num_publications", "name_sort")
        )

        return qs

    def by_readings(self, role_names=["", "Author"]):
        """
        The Creators who have been most-read, ordered by number of readings.

        By default it will only include Creators whose role was left empty,
        or is 'Author'.

        Each Creator will have a `num_readings` attribute.
        """
        if not spectator_apps.is_enabled("reading"):
            raise ImproperlyConfigured(
                "To use the CreatorManager.by_readings() method, 'spectator.reading' "
                "must by in INSTALLED_APPS."
            )

        qs = self.get_queryset()

        qs = (
            qs.filter(publication_roles__role_name__in=role_names)
            .filter(publications__reading__is_finished=True)
            .exclude(publications__reading__isnull=True)
            .annotate(num_readings=Count("publications__reading", distinct=True))
            .order_by("-num_readings", "name_sort")
        )

        return qs

    def by_events(self, kind=None):
        """
        Get the Creators involved in the most Events.

        This only counts Creators directly involved in an Event.
        i.e. if a Creator is the director of a movie Work, and an Event was
        a viewing of that movie, that Event wouldn't count. Unless they were
        also directly involved in the Event (e.g. speaking after the movie).

        kind - If supplied, only Events with that `kind` value will be counted.
        """
        if not spectator_apps.is_enabled("events"):
            raise ImproperlyConfigured(
                "To use the CreatorManager.by_events() method, 'spectator.events' "
                "must by in INSTALLED_APPS."
            )

        qs = self.get_queryset()

        if kind is not None:
            qs = qs.filter(events__kind=kind)

        qs = qs.annotate(num_events=Count("events", distinct=True)).order_by(
            "-num_events", "name_sort"
        )

        return qs

    def by_works(self, kind=None, role_name=None):
        """
        Get the Creators involved in the most Works.

        kind - If supplied, only Works with that `kind` value will be counted.
        role_name - If supplied, only Works on which the role is that will be counted.

        e.g. To get all 'movie' Works on which the Creators had the role 'Director':

            Creator.objects.by_works(kind='movie', role_name='Director')
        """
        if not spectator_apps.is_enabled("events"):
            raise ImproperlyConfigured(
                "To use the CreatorManager.by_works() method, 'spectator.events' "
                "must by in INSTALLED_APPS."
            )

        qs = self.get_queryset()

        filter_kwargs = {}

        if kind is not None:
            filter_kwargs["works__kind"] = kind

        if role_name is not None:
            filter_kwargs["work_roles__role_name"] = role_name

        if filter_kwargs:
            qs = qs.filter(**filter_kwargs)

        qs = qs.annotate(num_works=Count("works", distinct=True)).order_by(
            "-num_works", "name_sort"
        )

        return qs


text:
package eu.jpereira.trainings.designpatterns.structural.decorator.channel.decorator;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import eu.jpereira.trainings.designpatterns.structural.decorator.channel.SocialChannel;
import eu.jpereira.trainings.designpatterns.structural.decorator.channel.SocialChannelBuilder;
import eu.jpereira.trainings.designpatterns.structural.decorator.channel.SocialChannelProperties;
import eu.jpereira.trainings.designpatterns.structural.decorator.channel.SocialChannelPropertyKey;
import eu.jpereira.trainings.designpatterns.structural.decorator.channel.spy.TestSpySocialChannel;

/**
 * @author jpereira
 *
 */
public class MessageTruncatorTest extends AbstractSocialChanneldDecoratorTest{

	@Test
	public void testTruncate() {
		// Create the builder
		SocialChannelBuilder builder = createTestSpySocialChannelBuilder();

		// create a spy social channel
		SocialChannelProperties props = new SocialChannelProperties().putProperty(SocialChannelPropertyKey.NAME, TestSpySocialChannel.NAME);
		SocialChannel channel = builder.with(new MessageTruncator(10)).getDecoratedChannel(props);

		// Now call channel.deliverMessage
		channel.deliverMessage("this is a message");

		// Spy channel. Should get the one created before
		TestSpySocialChannel spyChannel = (TestSpySocialChannel) builder.buildChannel(props);
		assertEquals("this is...", spyChannel.lastMessagePublished());
	}

}


text:
require 'spec_helper'
include WebPageParser

describe ParserFactory do

  it "should load parsers in the parsers directory" do
    pfl = ParserFactory.factories.collect { |f| f.to_s }
    pfl.should include "TestPageParserFactory"
  end

  it "should provide the right PageParser for the given url" do
    ParserFactory.parser_for(:url => "http://www.example.com").should be_a_kind_of TestPageParser
  end

  it "should return nil if no PageParser can be found for the given url" do
    ParserFactory.parser_for(:url => "http://www.nowhere.nodomain").should be_nil
  end
end


text:
import {Component, ViewEncapsulation} from '@angular/core';
import * as Papa from 'papaparse/papaparse.min.js';
import {Subject} from "rxjs/Subject";
import {CodeNameService} from "../../codeName.service";
import {Router} from "@angular/router";
import {SharedService} from "../../../../services/shared.service";

@Component({
  selector: '',
  encapsulation: ViewEncapsulation.None,
  styleUrls: ['./codeNameImport.scss'],
  templateUrl: './codeNameImport.html',
})

export class CodeNameImport {

  dataSubject: Subject<any> = new Subject<any>();

  jsonData: any[] = [];
  cols: any[];

  constructor(protected service: CodeNameService,
              private router: Router,
              private sharedService: SharedService) {

  }

  ngOnInit() {
    this.cols = [
      {field: 'id', header: 'id'},
      {field: 'code', header: 'code'},
      {field: 'name', header: 'name'}
    ];
    this.dataSubject.subscribe(data => {
      this.jsonData = data;
    });
  }

  uploadHandler(event) {
    this.service.saveMany(this.jsonData).subscribe(
      (data) => {
        this.sharedService.addMessage({ severity: 'info', summary: 'Success', detail: 'Operation Success' });
        this.router.navigate(['/pages/codeName/table/']);
      }
    );
  }

  onSelect(event) {
    let file = event.files[0];
    let ds = this.dataSubject;
    Papa.parse(file, {
      skipEmptyLines:true,
      header: true,
      complete: function (results) {
        ds.next(results.data);
      }
    });
  }

}


text:
#pragma once

#include <cstdint>

#include <windows.h>
#include <hadesmem/detail/warning_disable_prefix.hpp>
#define DIRECTINPUT_VERSION 0x0800
#include <dinput.h>
#include <hadesmem/detail/warning_disable_suffix.hpp>

#include <hadesmem/config.hpp>

namespace hadesmem
{
namespace cerberus
{
class DirectInput8WProxy : public IDirectInput8W
{
public:
  explicit DirectInput8WProxy(IDirectInput8W* direct_input)
    : direct_input_{direct_input}
  {
  }

  // IUnknown
  HRESULT WINAPI QueryInterface(REFIID riid, LPVOID* obj) override;
  ULONG WINAPI AddRef() override;
  ULONG WINAPI Release() override;

  // IDirectInput8W
  HRESULT WINAPI CreateDevice(REFGUID rguid,
                              LPDIRECTINPUTDEVICE8W* lplpDirectInputDevice,
                              LPUNKNOWN pUnkOuter) override;
  HRESULT WINAPI EnumDevices(DWORD dwDevType,
                             LPDIENUMDEVICESCALLBACKW lpCallback,
                             LPVOID pvRef,
                             DWORD dwFlags) override;
  HRESULT WINAPI GetDeviceStatus(REFGUID rguidInstance) override;
  HRESULT WINAPI RunControlPanel(HWND hwndOwner, DWORD dwFlags) override;
  HRESULT WINAPI Initialize(HINSTANCE hinst, DWORD dwVersion) override;
  HRESULT WINAPI FindDevice(REFGUID rguidClass,
                            LPCTSTR ptszName,
                            LPGUID pguidInstance) override;
  HRESULT WINAPI EnumDevicesBySemantics(LPCTSTR ptszUserName,
                                        LPDIACTIONFORMAT lpdiActionFormat,
                                        LPDIENUMDEVICESBYSEMANTICSCB lpCallback,
                                        LPVOID pvRef,
                                        DWORD dwFlags) override;
  HRESULT WINAPI ConfigureDevices(LPDICONFIGUREDEVICESCALLBACK lpdiCallback,
                                  LPDICONFIGUREDEVICESPARAMS lpdiCDParams,
                                  DWORD dwFlags,
                                  LPVOID pvRefData) override;

private:
  void Cleanup();

  std::int64_t refs_{1};
  IDirectInput8W* direct_input_{};
};
}
}