<commit_before>/*
 * Copyright (C) 2013 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "modules/speech/SpeechSynthesis.h"

#include "bindings/v8/ExceptionState.h"
#include "core/dom/ExecutionContext.h"
#include "modules/speech/SpeechSynthesisEvent.h"
#include "platform/speech/PlatformSpeechSynthesisVoice.h"
#include "wtf/CurrentTime.h"

namespace WebCore {

PassRefPtrWillBeRawPtr<SpeechSynthesis> SpeechSynthesis::create(ExecutionContext* context)
{
    return adoptRefWillBeNoop(new SpeechSynthesis(context));
}

SpeechSynthesis::SpeechSynthesis(ExecutionContext* context)
    : ContextLifecycleObserver(context)
    , m_platformSpeechSynthesizer(PlatformSpeechSynthesizer::create(this))
    , m_isPaused(false)
{
    ScriptWrappable::init(this);
}

void SpeechSynthesis::setPlatformSynthesizer(PassOwnPtr<PlatformSpeechSynthesizer> synthesizer)
{
    m_platformSpeechSynthesizer = synthesizer;
}

ExecutionContext* SpeechSynthesis::executionContext() const
{
    return ContextLifecycleObserver::executionContext();
}

void SpeechSynthesis::voicesDidChange()
{
    m_voiceList.clear();
    if (!executionContext()->activeDOMObjectsAreStopped())
        dispatchEvent(Event::create(EventTypeNames::voiceschanged));
}

const WillBeHeapVector<RefPtrWillBeMember<SpeechSynthesisVoice> >& SpeechSynthesis::getVoices()
{
    if (m_voiceList.size())
        return m_voiceList;

    // If the voiceList is empty, that's the cue to get the voices from the platform again.
    const Vector<RefPtr<PlatformSpeechSynthesisVoice> >& platformVoices = m_platformSpeechSynthesizer->voiceList();
    size_t voiceCount = platformVoices.size();
    for (size_t k = 0; k < voiceCount; k++)
        m_voiceList.append(SpeechSynthesisVoice::create(platformVoices[k]));

    return m_voiceList;
}

bool SpeechSynthesis::speaking() const
{
    // If we have a current speech utterance, then that means we're assumed to be in a speaking state.
    // This state is independent of whether the utterance happens to be paused.
    return currentSpeechUtterance();
}

bool SpeechSynthesis::pending() const
{
    // This is true if there are any utterances that have not started.
    // That means there will be more than one in the queue.
    return m_utteranceQueue.size() > 1;
}

bool SpeechSynthesis::paused() const
{
    return m_isPaused;
}

void SpeechSynthesis::startSpeakingImmediately()
{
    SpeechSynthesisUtterance* utterance = currentSpeechUtterance();
    ASSERT(utterance);

    utterance->setStartTime(monotonicallyIncreasingTime());
    m_isPaused = false;
    m_platformSpeechSynthesizer->speak(utterance->platformUtterance());
}

void SpeechSynthesis::speak(SpeechSynthesisUtterance* utterance, ExceptionState& exceptionState)
{
    if (!utterance) {
        exceptionState.throwTypeError("Invalid utterance argument");
        return;
    }

    m_utteranceQueue.append(utterance);

    // If the queue was empty, speak this immediately.
    if (m_utteranceQueue.size() == 1)
        startSpeakingImmediately();
}

void SpeechSynthesis::cancel()
{
    // Remove all the items from the utterance queue. The platform
    // may still have references to some of these utterances and may
    // fire events on them asynchronously.
    m_utteranceQueue.clear();
    m_platformSpeechSynthesizer->cancel();
}

void SpeechSynthesis::pause()
{
    if (!m_isPaused)
        m_platformSpeechSynthesizer->pause();
}

void SpeechSynthesis::resume()
{
    if (!currentSpeechUtterance())
        return;
    m_platformSpeechSynthesizer->resume();
}

void SpeechSynthesis::fireEvent(const AtomicString& type, SpeechSynthesisUtterance* utterance, unsigned long charIndex, const String& name)
{
    if (!executionContext()->activeDOMObjectsAreStopped())
        utterance->dispatchEvent(SpeechSynthesisEvent::create(type, charIndex, (currentTime() - utterance->startTime()), name));
}

void SpeechSynthesis::handleSpeakingCompleted(SpeechSynthesisUtterance* utterance, bool errorOccurred)
{
    ASSERT(utterance);

    // Keep the utterance around long enough to fire an event on it in case m_utteranceQueue
    // is holding the last reference to it.
    RefPtrWillBeRawPtr<SpeechSynthesisUtterance> protect(utterance);

    bool didJustFinishCurrentUtterance = false;
    // If the utterance that completed was the one we're currently speaking,
    // remove it from the queue and start speaking the next one.
    if (utterance == currentSpeechUtterance()) {
        m_utteranceQueue.removeFirst();
        didJustFinishCurrentUtterance = true;
    }

    // Always fire the event, because the platform may have asynchronously
    // sent an event on an utterance before it got the message that we
    // canceled it, and we should always report to the user what actually
    // happened.
    fireEvent(errorOccurred ? EventTypeNames::error : EventTypeNames::end, utterance, 0, String());

    // Start the next utterance if we just finished one and one was pending.
    if (didJustFinishCurrentUtterance && !m_utteranceQueue.isEmpty())
        startSpeakingImmediately();
}

void SpeechSynthesis::boundaryEventOccurred(PassRefPtr<PlatformSpeechSynthesisUtterance> utterance, SpeechBoundary boundary, unsigned charIndex)
{
    DEFINE_STATIC_LOCAL(const String, wordBoundaryString, ("word"));
    DEFINE_STATIC_LOCAL(const String, sentenceBoundaryString, ("sentence"));

    switch (boundary) {
    case SpeechWordBoundary:
        fireEvent(EventTypeNames::boundary, static_cast<SpeechSynthesisUtterance*>(utterance->client()), charIndex, wordBoundaryString);
        break;
    case SpeechSentenceBoundary:
        fireEvent(EventTypeNames::boundary, static_cast<SpeechSynthesisUtterance*>(utterance->client()), charIndex, sentenceBoundaryString);
        break;
    default:
        ASSERT_NOT_REACHED();
    }
}

void SpeechSynthesis::didStartSpeaking(PassRefPtr<PlatformSpeechSynthesisUtterance> utterance)
{
    if (utterance->client())
        fireEvent(EventTypeNames::start, static_cast<SpeechSynthesisUtterance*>(utterance->client()), 0, String());
}

void SpeechSynthesis::didPauseSpeaking(PassRefPtr<PlatformSpeechSynthesisUtterance> utterance)
{
    m_isPaused = true;
    if (utterance->client())
        fireEvent(EventTypeNames::pause, static_cast<SpeechSynthesisUtterance*>(utterance->client()), 0, String());
}

void SpeechSynthesis::didResumeSpeaking(PassRefPtr<PlatformSpeechSynthesisUtterance> utterance)
{
    m_isPaused = false;
    if (utterance->client())
        fireEvent(EventTypeNames::resume, static_cast<SpeechSynthesisUtterance*>(utterance->client()), 0, String());
}

void SpeechSynthesis::didFinishSpeaking(PassRefPtr<PlatformSpeechSynthesisUtterance> utterance)
{
    if (utterance->client())
        handleSpeakingCompleted(static_cast<SpeechSynthesisUtterance*>(utterance->client()), false);
}

void SpeechSynthesis::speakingErrorOccurred(PassRefPtr<PlatformSpeechSynthesisUtterance> utterance)
{
    if (utterance->client())
        handleSpeakingCompleted(static_cast<SpeechSynthesisUtterance*>(utterance->client()), true);
}

SpeechSynthesisUtterance* SpeechSynthesis::currentSpeechUtterance() const
{
    if (!m_utteranceQueue.isEmpty())
        return m_utteranceQueue.first().get();
    return 0;
}

const AtomicString& SpeechSynthesis::interfaceName() const
{
    return EventTargetNames::SpeechSynthesisUtterance;
}

void SpeechSynthesis::trace(Visitor* visitor)
{
    visitor->trace(m_voiceList);
    visitor->trace(m_utteranceQueue);
    EventTargetWithInlineData::trace(visitor);
}

} // namespace WebCore
<commit_msg>Make SpeechSynthesis gracefully handle ExecutionContext-less operation.<commit_after>/*
 * Copyright (C) 2013 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "modules/speech/SpeechSynthesis.h"

#include "bindings/v8/ExceptionState.h"
#include "core/dom/ExecutionContext.h"
#include "modules/speech/SpeechSynthesisEvent.h"
#include "platform/speech/PlatformSpeechSynthesisVoice.h"
#include "wtf/CurrentTime.h"

namespace WebCore {

PassRefPtrWillBeRawPtr<SpeechSynthesis> SpeechSynthesis::create(ExecutionContext* context)
{
    return adoptRefWillBeNoop(new SpeechSynthesis(context));
}

SpeechSynthesis::SpeechSynthesis(ExecutionContext* context)
    : ContextLifecycleObserver(context)
    , m_platformSpeechSynthesizer(PlatformSpeechSynthesizer::create(this))
    , m_isPaused(false)
{
    ScriptWrappable::init(this);
}

void SpeechSynthesis::setPlatformSynthesizer(PassOwnPtr<PlatformSpeechSynthesizer> synthesizer)
{
    m_platformSpeechSynthesizer = synthesizer;
}

ExecutionContext* SpeechSynthesis::executionContext() const
{
    return ContextLifecycleObserver::executionContext();
}

void SpeechSynthesis::voicesDidChange()
{
    m_voiceList.clear();
    if (executionContext() && !executionContext()->activeDOMObjectsAreStopped())
        dispatchEvent(Event::create(EventTypeNames::voiceschanged));
}

const WillBeHeapVector<RefPtrWillBeMember<SpeechSynthesisVoice> >& SpeechSynthesis::getVoices()
{
    if (m_voiceList.size())
        return m_voiceList;

    // If the voiceList is empty, that's the cue to get the voices from the platform again.
    const Vector<RefPtr<PlatformSpeechSynthesisVoice> >& platformVoices = m_platformSpeechSynthesizer->voiceList();
    size_t voiceCount = platformVoices.size();
    for (size_t k = 0; k < voiceCount; k++)
        m_voiceList.append(SpeechSynthesisVoice::create(platformVoices[k]));

    return m_voiceList;
}

bool SpeechSynthesis::speaking() const
{
    // If we have a current speech utterance, then that means we're assumed to be in a speaking state.
    // This state is independent of whether the utterance happens to be paused.
    return currentSpeechUtterance();
}

bool SpeechSynthesis::pending() const
{
    // This is true if there are any utterances that have not started.
    // That means there will be more than one in the queue.
    return m_utteranceQueue.size() > 1;
}

bool SpeechSynthesis::paused() const
{
    return m_isPaused;
}

void SpeechSynthesis::startSpeakingImmediately()
{
    SpeechSynthesisUtterance* utterance = currentSpeechUtterance();
    ASSERT(utterance);

    utterance->setStartTime(monotonicallyIncreasingTime());
    m_isPaused = false;
    m_platformSpeechSynthesizer->speak(utterance->platformUtterance());
}

void SpeechSynthesis::speak(SpeechSynthesisUtterance* utterance, ExceptionState& exceptionState)
{
    if (!utterance) {
        exceptionState.throwTypeError("Invalid utterance argument");
        return;
    }

    m_utteranceQueue.append(utterance);

    // If the queue was empty, speak this immediately.
    if (m_utteranceQueue.size() == 1)
        startSpeakingImmediately();
}

void SpeechSynthesis::cancel()
{
    // Remove all the items from the utterance queue. The platform
    // may still have references to some of these utterances and may
    // fire events on them asynchronously.
    m_utteranceQueue.clear();
    m_platformSpeechSynthesizer->cancel();
}

void SpeechSynthesis::pause()
{
    if (!m_isPaused)
        m_platformSpeechSynthesizer->pause();
}

void SpeechSynthesis::resume()
{
    if (!currentSpeechUtterance())
        return;
    m_platformSpeechSynthesizer->resume();
}

void SpeechSynthesis::fireEvent(const AtomicString& type, SpeechSynthesisUtterance* utterance, unsigned long charIndex, const String& name)
{
    if (executionContext() && !executionContext()->activeDOMObjectsAreStopped())
        utterance->dispatchEvent(SpeechSynthesisEvent::create(type, charIndex, (currentTime() - utterance->startTime()), name));
}

void SpeechSynthesis::handleSpeakingCompleted(SpeechSynthesisUtterance* utterance, bool errorOccurred)
{
    ASSERT(utterance);

    // Keep the utterance around long enough to fire an event on it in case m_utteranceQueue
    // is holding the last reference to it.
    RefPtrWillBeRawPtr<SpeechSynthesisUtterance> protect(utterance);

    bool didJustFinishCurrentUtterance = false;
    // If the utterance that completed was the one we're currently speaking,
    // remove it from the queue and start speaking the next one.
    if (utterance == currentSpeechUtterance()) {
        m_utteranceQueue.removeFirst();
        didJustFinishCurrentUtterance = true;
    }

    // Always fire the event, because the platform may have asynchronously
    // sent an event on an utterance before it got the message that we
    // canceled it, and we should always report to the user what actually
    // happened.
    fireEvent(errorOccurred ? EventTypeNames::error : EventTypeNames::end, utterance, 0, String());

    // Start the next utterance if we just finished one and one was pending.
    if (didJustFinishCurrentUtterance && !m_utteranceQueue.isEmpty())
        startSpeakingImmediately();
}

void SpeechSynthesis::boundaryEventOccurred(PassRefPtr<PlatformSpeechSynthesisUtterance> utterance, SpeechBoundary boundary, unsigned charIndex)
{
    DEFINE_STATIC_LOCAL(const String, wordBoundaryString, ("word"));
    DEFINE_STATIC_LOCAL(const String, sentenceBoundaryString, ("sentence"));

    switch (boundary) {
    case SpeechWordBoundary:
        fireEvent(EventTypeNames::boundary, static_cast<SpeechSynthesisUtterance*>(utterance->client()), charIndex, wordBoundaryString);
        break;
    case SpeechSentenceBoundary:
        fireEvent(EventTypeNames::boundary, static_cast<SpeechSynthesisUtterance*>(utterance->client()), charIndex, sentenceBoundaryString);
        break;
    default:
        ASSERT_NOT_REACHED();
    }
}

void SpeechSynthesis::didStartSpeaking(PassRefPtr<PlatformSpeechSynthesisUtterance> utterance)
{
    if (utterance->client())
        fireEvent(EventTypeNames::start, static_cast<SpeechSynthesisUtterance*>(utterance->client()), 0, String());
}

void SpeechSynthesis::didPauseSpeaking(PassRefPtr<PlatformSpeechSynthesisUtterance> utterance)
{
    m_isPaused = true;
    if (utterance->client())
        fireEvent(EventTypeNames::pause, static_cast<SpeechSynthesisUtterance*>(utterance->client()), 0, String());
}

void SpeechSynthesis::didResumeSpeaking(PassRefPtr<PlatformSpeechSynthesisUtterance> utterance)
{
    m_isPaused = false;
    if (utterance->client())
        fireEvent(EventTypeNames::resume, static_cast<SpeechSynthesisUtterance*>(utterance->client()), 0, String());
}

void SpeechSynthesis::didFinishSpeaking(PassRefPtr<PlatformSpeechSynthesisUtterance> utterance)
{
    if (utterance->client())
        handleSpeakingCompleted(static_cast<SpeechSynthesisUtterance*>(utterance->client()), false);
}

void SpeechSynthesis::speakingErrorOccurred(PassRefPtr<PlatformSpeechSynthesisUtterance> utterance)
{
    if (utterance->client())
        handleSpeakingCompleted(static_cast<SpeechSynthesisUtterance*>(utterance->client()), true);
}

SpeechSynthesisUtterance* SpeechSynthesis::currentSpeechUtterance() const
{
    if (!m_utteranceQueue.isEmpty())
        return m_utteranceQueue.first().get();
    return 0;
}

const AtomicString& SpeechSynthesis::interfaceName() const
{
    return EventTargetNames::SpeechSynthesisUtterance;
}

void SpeechSynthesis::trace(Visitor* visitor)
{
    visitor->trace(m_voiceList);
    visitor->trace(m_utteranceQueue);
    EventTargetWithInlineData::trace(visitor);
}

} // namespace WebCore
<|endoftext|>


<commit_before>// @(#)root/reflex:$Name:  $:$Id: test_Reflex_simple1.cxx,v 1.17 2007/04/16 13:19:07 axel Exp $
// Author: Stefan Roiser 2004

// CppUnit include file
#include "cppunit/extensions/HelperMacros.h"

// Seal include files
#include "Reflex/Reflex.h"

// Standard C++ include files
#include <iostream>
#include <iomanip>
#include <limits>
#ifdef _WIN32
  #include<windows.h>
#else
  #include<dlfcn.h>
#endif

using namespace ROOT::Reflex;

/**
 * test_Reflex_simple1.cpp
 * testing Reflex with the dictionary of Reflex itself
 */

class ReflexSimple1Test : public CppUnit::TestFixture {

  CPPUNIT_TEST_SUITE( ReflexSimple1Test );

  CPPUNIT_TEST( loadLibrary );
  CPPUNIT_TEST( testSizeT );
  CPPUNIT_TEST( testBase );
  CPPUNIT_TEST( testTypeCount );
  CPPUNIT_TEST( testMembers );
  CPPUNIT_TEST( testVirtual );
  CPPUNIT_TEST( unloadLibrary );
  CPPUNIT_TEST( shutdown );

  CPPUNIT_TEST_SUITE_END();

public:

  void setUp() {}

  void loadLibrary();
  void testSizeT();
  void testBase();
  void testTypeCount();
  void testMembers();
  void testVirtual();
  void unloadLibrary();
  void shutdown() { Reflex::Shutdown(); }

  void tearDown() {}

}; // class ReflesSimple1Test

#if defined (_WIN32)
static HMODULE s_libInstance = 0;
#else
static void * s_libInstance = 0;
#endif

void ReflexSimple1Test::loadLibrary() {
#if defined (_WIN32)
  s_libInstance = LoadLibrary("libtest_ReflexRflx.dll");
#else
  s_libInstance = dlopen("libtest_ReflexRflx.so", RTLD_NOW);
  if ( ! s_libInstance ) std::cout << dlerror() << std::endl;
#endif
  CPPUNIT_ASSERT( s_libInstance );
}

void ReflexSimple1Test::testSizeT() {

  Type t = Type::ByName("size_t");
  CPPUNIT_ASSERT(t);
#if defined(__GNUC__)
#if (__GNUC__ <= 3) && (!__x86_64__)
  std::string size_t_T = "j";
#else
  std::string size_t_T = "m";
#endif
#elif defined(_WIN32)
  std::string size_t_T = "unsigned int";
#endif
  CPPUNIT_ASSERT_EQUAL(size_t_T,std::string(t.TypeInfo().name()));
  CPPUNIT_ASSERT_EQUAL(size_t_T,std::string(t.ToType().TypeInfo().name()));
}

void ReflexSimple1Test::testBase() {

  Type t1 = Type::ByName("ROOT::Reflex::ScopeName");
  Type t2 = Type::ByName("ROOT::Reflex::ScopeBase");

  CPPUNIT_ASSERT(t1);
  CPPUNIT_ASSERT(t2);

  CPPUNIT_ASSERT_EQUAL(std::string(""), t1.ToType().Name());
  CPPUNIT_ASSERT_EQUAL(t1.Name(), t1.FinalType().Name());
  CPPUNIT_ASSERT_EQUAL(t1.Name(), t1.RawType().Name());

  CPPUNIT_ASSERT(!t1.HasBase(t2));
  CPPUNIT_ASSERT(!t2.HasBase(t1));
}

void ReflexSimple1Test::testTypeCount() {
  CPPUNIT_ASSERT( (int(Type::TypeSize()) > 500) && (int(Type::TypeSize()) < 1000) );
}

void ReflexSimple1Test::testMembers() {

  Member m;
  Type t = Type::ByName("ROOT::Reflex::PropertyList");

  CPPUNIT_ASSERT(t);
  CPPUNIT_ASSERT(t.Id());
  CPPUNIT_ASSERT(t.IsClass());
  CPPUNIT_ASSERT_EQUAL(std::string("PropertyList"),t.Name());
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::PropertyList"), t.Name(SCOPED));

  Object o = t.Construct();

  CPPUNIT_ASSERT(o);
  CPPUNIT_ASSERT(o.Address());

  CPPUNIT_ASSERT_EQUAL(1, int(t.DataMemberSize()));
  CPPUNIT_ASSERT_EQUAL(31, int(t.FunctionMemberSize()));
  CPPUNIT_ASSERT_EQUAL(32, int(t.MemberSize()));

  t.UpdateMembers();

  CPPUNIT_ASSERT_EQUAL(1, int(t.DataMemberSize()));
  CPPUNIT_ASSERT_EQUAL(31, int(t.FunctionMemberSize()));
  CPPUNIT_ASSERT_EQUAL(32, int(t.MemberSize()));

  m = t.DataMemberAt(0);
  CPPUNIT_ASSERT(m);
  CPPUNIT_ASSERT_EQUAL(std::string("fPropertyListImpl"), m.Name());
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::PropertyList::fPropertyListImpl"), m.Name(SCOPED));
  CPPUNIT_ASSERT_EQUAL((void*)0, Object_Cast<void*>(m.Get(o)));

  m = t.FunctionMemberAt(0);
  CPPUNIT_ASSERT(m);
  CPPUNIT_ASSERT_EQUAL(std::string("PropertyList"), m.Name());
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::PropertyList::PropertyList"), m.Name(SCOPED));
  CPPUNIT_ASSERT(m.IsConstructor());
  CPPUNIT_ASSERT(!m.IsDestructor());

  m = t.FunctionMemberAt(1);
  CPPUNIT_ASSERT(m);
  CPPUNIT_ASSERT_EQUAL(std::string("PropertyList"), m.Name());
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::PropertyList::PropertyList"), m.Name(SCOPED));
  CPPUNIT_ASSERT(m.IsConstructor());
  CPPUNIT_ASSERT(!m.IsDestructor());

  m = t.FunctionMemberAt(2);
  CPPUNIT_ASSERT(m);
  CPPUNIT_ASSERT_EQUAL(std::string("~PropertyList"), m.Name());
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::PropertyList::~PropertyList"), m.Name(SCOPED));
  CPPUNIT_ASSERT(!m.IsConstructor());
  CPPUNIT_ASSERT(m.IsDestructor());

  m = t.FunctionMemberAt(3);
  CPPUNIT_ASSERT(m);
  CPPUNIT_ASSERT_EQUAL(std::string("operator bool"), m.Name());
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::PropertyList::operator bool"), m.Name(SCOPED));
  CPPUNIT_ASSERT(!m.IsConstructor());
  CPPUNIT_ASSERT(!m.IsDestructor());

  m = t.FunctionMemberAt(4);
  CPPUNIT_ASSERT(m);
  CPPUNIT_ASSERT_EQUAL(std::string("AddProperty"), m.Name());
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::PropertyList::AddProperty"), m.Name(SCOPED));
  CPPUNIT_ASSERT(!m.IsConstructor());
  CPPUNIT_ASSERT(!m.IsDestructor());

  m = t.FunctionMemberAt(5);
  CPPUNIT_ASSERT(m);
  CPPUNIT_ASSERT_EQUAL(std::string("AddProperty"), m.Name());
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::PropertyList::AddProperty"), m.Name(SCOPED));
  CPPUNIT_ASSERT(!m.IsConstructor());
  CPPUNIT_ASSERT(!m.IsDestructor());

  m = t.FunctionMemberAt(6);
  CPPUNIT_ASSERT(m);
  CPPUNIT_ASSERT_EQUAL(std::string("AddProperty"), m.Name());
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::PropertyList::AddProperty"), m.Name(SCOPED));
  CPPUNIT_ASSERT(!m.IsConstructor());
  CPPUNIT_ASSERT(!m.IsDestructor());

  m = t.FunctionMemberAt(7);
  CPPUNIT_ASSERT(m);
  CPPUNIT_ASSERT_EQUAL(std::string("AddProperty"), m.Name());
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::PropertyList::AddProperty"), m.Name(SCOPED));
  CPPUNIT_ASSERT(!m.IsConstructor());
  CPPUNIT_ASSERT(!m.IsDestructor());

  m = t.FunctionMemberAt(8);
  CPPUNIT_ASSERT(m);
  CPPUNIT_ASSERT_EQUAL(std::string("ClearProperties"), m.Name());
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::PropertyList::ClearProperties"), m.Name(SCOPED));
  CPPUNIT_ASSERT(!m.IsConstructor());
  CPPUNIT_ASSERT(!m.IsDestructor());

  m = t.FunctionMemberAt(9);
  CPPUNIT_ASSERT(m);
  CPPUNIT_ASSERT_EQUAL(std::string("HasKey"), m.Name());
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::PropertyList::HasKey"), m.Name(SCOPED));
  CPPUNIT_ASSERT(!m.IsConstructor());
  CPPUNIT_ASSERT(!m.IsDestructor());

  m = t.FunctionMemberAt(10);
  CPPUNIT_ASSERT(m);
  CPPUNIT_ASSERT_EQUAL(std::string("HasProperty"), m.Name());
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::PropertyList::HasProperty"), m.Name(SCOPED));
  CPPUNIT_ASSERT(!m.IsConstructor());
  CPPUNIT_ASSERT(!m.IsDestructor());

  m = t.FunctionMemberAt(11);
  CPPUNIT_ASSERT(m);
  CPPUNIT_ASSERT_EQUAL(std::string("HasProperty"), m.Name());
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::PropertyList::HasProperty"), m.Name(SCOPED));
  CPPUNIT_ASSERT(!m.IsConstructor());
  CPPUNIT_ASSERT(!m.IsDestructor());

  m = t.FunctionMemberAt(12);
  CPPUNIT_ASSERT(m);
  CPPUNIT_ASSERT_EQUAL(std::string("Key_Begin"), m.Name());
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::PropertyList::Key_Begin"), m.Name(SCOPED));
  CPPUNIT_ASSERT(!m.IsConstructor());
  CPPUNIT_ASSERT(!m.IsDestructor());

  m = t.FunctionMemberAt(13);
  CPPUNIT_ASSERT(m);
  CPPUNIT_ASSERT_EQUAL(std::string("Key_End"), m.Name());
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::PropertyList::Key_End"), m.Name(SCOPED));
  CPPUNIT_ASSERT(!m.IsConstructor());
  CPPUNIT_ASSERT(!m.IsDestructor());

  o.Destruct();
  CPPUNIT_ASSERT(!o);
}

void ReflexSimple1Test::testVirtual() {

  Type t1 = Type::ByName("ROOT::Reflex::Type");
  Type t2 = Type::ByName("ROOT::Reflex::TypeBase");

  CPPUNIT_ASSERT(t1);
  CPPUNIT_ASSERT_EQUAL(std::string("Type"),t1.Name());
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::Type"), t1.Name(SCOPED));
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::Type"), t1.Name(SCOPED|QUALIFIED|FINAL));
  CPPUNIT_ASSERT(!t1.IsVirtual());
  CPPUNIT_ASSERT(t2);
  CPPUNIT_ASSERT_EQUAL(std::string("TypeBase"),t2.Name());
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::TypeBase"), t2.Name(SCOPED));
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::TypeBase"), t2.Name(SCOPED|QUALIFIED|FINAL));
  CPPUNIT_ASSERT(t2.IsVirtual());

}

void ReflexSimple1Test::unloadLibrary() {
#if defined (_WIN32)
  int ret = FreeLibrary(s_libInstance);
  if (ret == 0) std::cout << "Unload of dictionary library failed. Reason: " << GetLastError() << std::endl;
  CPPUNIT_ASSERT(ret);
#else
  int ret = dlclose(s_libInstance);
  if (ret == -1) std::cout << "Unload of dictionary library failed. Reason: " << dlerror() << std::endl;
  CPPUNIT_ASSERT(!ret);
#endif
  //std::cout << "Endless" << std::endl;
  //while (true) {}

}

// Class registration on cppunit framework
CPPUNIT_TEST_SUITE_REGISTRATION(ReflexSimple1Test);

// CppUnit test-driver common for all the cppunit test classes
#include<CppUnit_testdriver.cpp>
<commit_msg>Update the number of func members of PropertyList: now has __getNewDelFunctions<commit_after>// @(#)root/reflex:$Name:  $:$Id: test_Reflex_simple1.cxx,v 1.18 2007/04/26 13:55:43 axel Exp $
// Author: Stefan Roiser 2004

// CppUnit include file
#include "cppunit/extensions/HelperMacros.h"

// Seal include files
#include "Reflex/Reflex.h"

// Standard C++ include files
#include <iostream>
#include <iomanip>
#include <limits>
#ifdef _WIN32
  #include<windows.h>
#else
  #include<dlfcn.h>
#endif

using namespace ROOT::Reflex;

/**
 * test_Reflex_simple1.cpp
 * testing Reflex with the dictionary of Reflex itself
 */

class ReflexSimple1Test : public CppUnit::TestFixture {

  CPPUNIT_TEST_SUITE( ReflexSimple1Test );

  CPPUNIT_TEST( loadLibrary );
  CPPUNIT_TEST( testSizeT );
  CPPUNIT_TEST( testBase );
  CPPUNIT_TEST( testTypeCount );
  CPPUNIT_TEST( testMembers );
  CPPUNIT_TEST( testVirtual );
  CPPUNIT_TEST( unloadLibrary );
  CPPUNIT_TEST( shutdown );

  CPPUNIT_TEST_SUITE_END();

public:

  void setUp() {}

  void loadLibrary();
  void testSizeT();
  void testBase();
  void testTypeCount();
  void testMembers();
  void testVirtual();
  void unloadLibrary();
  void shutdown() { Reflex::Shutdown(); }

  void tearDown() {}

}; // class ReflesSimple1Test

#if defined (_WIN32)
static HMODULE s_libInstance = 0;
#else
static void * s_libInstance = 0;
#endif

void ReflexSimple1Test::loadLibrary() {
#if defined (_WIN32)
  s_libInstance = LoadLibrary("libtest_ReflexRflx.dll");
#else
  s_libInstance = dlopen("libtest_ReflexRflx.so", RTLD_NOW);
  if ( ! s_libInstance ) std::cout << dlerror() << std::endl;
#endif
  CPPUNIT_ASSERT( s_libInstance );
}

void ReflexSimple1Test::testSizeT() {

  Type t = Type::ByName("size_t");
  CPPUNIT_ASSERT(t);
#if defined(__GNUC__)
#if (__GNUC__ <= 3) && (!__x86_64__)
  std::string size_t_T = "j";
#else
  std::string size_t_T = "m";
#endif
#elif defined(_WIN32)
  std::string size_t_T = "unsigned int";
#endif
  CPPUNIT_ASSERT_EQUAL(size_t_T,std::string(t.TypeInfo().name()));
  CPPUNIT_ASSERT_EQUAL(size_t_T,std::string(t.ToType().TypeInfo().name()));
}

void ReflexSimple1Test::testBase() {

  Type t1 = Type::ByName("ROOT::Reflex::ScopeName");
  Type t2 = Type::ByName("ROOT::Reflex::ScopeBase");

  CPPUNIT_ASSERT(t1);
  CPPUNIT_ASSERT(t2);

  CPPUNIT_ASSERT_EQUAL(std::string(""), t1.ToType().Name());
  CPPUNIT_ASSERT_EQUAL(t1.Name(), t1.FinalType().Name());
  CPPUNIT_ASSERT_EQUAL(t1.Name(), t1.RawType().Name());

  CPPUNIT_ASSERT(!t1.HasBase(t2));
  CPPUNIT_ASSERT(!t2.HasBase(t1));
}

void ReflexSimple1Test::testTypeCount() {
  CPPUNIT_ASSERT( (int(Type::TypeSize()) > 500) && (int(Type::TypeSize()) < 1000) );
}

void ReflexSimple1Test::testMembers() {

  Member m;
  Type t = Type::ByName("ROOT::Reflex::PropertyList");

  CPPUNIT_ASSERT(t);
  CPPUNIT_ASSERT(t.Id());
  CPPUNIT_ASSERT(t.IsClass());
  CPPUNIT_ASSERT_EQUAL(std::string("PropertyList"),t.Name());
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::PropertyList"), t.Name(SCOPED));

  Object o = t.Construct();

  CPPUNIT_ASSERT(o);
  CPPUNIT_ASSERT(o.Address());

  CPPUNIT_ASSERT_EQUAL(1, int(t.DataMemberSize()));
  CPPUNIT_ASSERT_EQUAL(32, int(t.FunctionMemberSize()));
  CPPUNIT_ASSERT_EQUAL(33, int(t.MemberSize()));

  t.UpdateMembers();

  CPPUNIT_ASSERT_EQUAL(1, int(t.DataMemberSize()));
  CPPUNIT_ASSERT_EQUAL(32, int(t.FunctionMemberSize()));
  CPPUNIT_ASSERT_EQUAL(33, int(t.MemberSize()));

  m = t.DataMemberAt(0);
  CPPUNIT_ASSERT(m);
  CPPUNIT_ASSERT_EQUAL(std::string("fPropertyListImpl"), m.Name());
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::PropertyList::fPropertyListImpl"), m.Name(SCOPED));
  CPPUNIT_ASSERT_EQUAL((void*)0, Object_Cast<void*>(m.Get(o)));

  m = t.FunctionMemberAt(0);
  CPPUNIT_ASSERT(m);
  CPPUNIT_ASSERT_EQUAL(std::string("PropertyList"), m.Name());
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::PropertyList::PropertyList"), m.Name(SCOPED));
  CPPUNIT_ASSERT(m.IsConstructor());
  CPPUNIT_ASSERT(!m.IsDestructor());

  m = t.FunctionMemberAt(1);
  CPPUNIT_ASSERT(m);
  CPPUNIT_ASSERT_EQUAL(std::string("PropertyList"), m.Name());
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::PropertyList::PropertyList"), m.Name(SCOPED));
  CPPUNIT_ASSERT(m.IsConstructor());
  CPPUNIT_ASSERT(!m.IsDestructor());

  m = t.FunctionMemberAt(2);
  CPPUNIT_ASSERT(m);
  CPPUNIT_ASSERT_EQUAL(std::string("~PropertyList"), m.Name());
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::PropertyList::~PropertyList"), m.Name(SCOPED));
  CPPUNIT_ASSERT(!m.IsConstructor());
  CPPUNIT_ASSERT(m.IsDestructor());

  m = t.FunctionMemberAt(3);
  CPPUNIT_ASSERT(m);
  CPPUNIT_ASSERT_EQUAL(std::string("operator bool"), m.Name());
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::PropertyList::operator bool"), m.Name(SCOPED));
  CPPUNIT_ASSERT(!m.IsConstructor());
  CPPUNIT_ASSERT(!m.IsDestructor());

  m = t.FunctionMemberAt(4);
  CPPUNIT_ASSERT(m);
  CPPUNIT_ASSERT_EQUAL(std::string("AddProperty"), m.Name());
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::PropertyList::AddProperty"), m.Name(SCOPED));
  CPPUNIT_ASSERT(!m.IsConstructor());
  CPPUNIT_ASSERT(!m.IsDestructor());

  m = t.FunctionMemberAt(5);
  CPPUNIT_ASSERT(m);
  CPPUNIT_ASSERT_EQUAL(std::string("AddProperty"), m.Name());
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::PropertyList::AddProperty"), m.Name(SCOPED));
  CPPUNIT_ASSERT(!m.IsConstructor());
  CPPUNIT_ASSERT(!m.IsDestructor());

  m = t.FunctionMemberAt(6);
  CPPUNIT_ASSERT(m);
  CPPUNIT_ASSERT_EQUAL(std::string("AddProperty"), m.Name());
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::PropertyList::AddProperty"), m.Name(SCOPED));
  CPPUNIT_ASSERT(!m.IsConstructor());
  CPPUNIT_ASSERT(!m.IsDestructor());

  m = t.FunctionMemberAt(7);
  CPPUNIT_ASSERT(m);
  CPPUNIT_ASSERT_EQUAL(std::string("AddProperty"), m.Name());
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::PropertyList::AddProperty"), m.Name(SCOPED));
  CPPUNIT_ASSERT(!m.IsConstructor());
  CPPUNIT_ASSERT(!m.IsDestructor());

  m = t.FunctionMemberAt(8);
  CPPUNIT_ASSERT(m);
  CPPUNIT_ASSERT_EQUAL(std::string("ClearProperties"), m.Name());
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::PropertyList::ClearProperties"), m.Name(SCOPED));
  CPPUNIT_ASSERT(!m.IsConstructor());
  CPPUNIT_ASSERT(!m.IsDestructor());

  m = t.FunctionMemberAt(9);
  CPPUNIT_ASSERT(m);
  CPPUNIT_ASSERT_EQUAL(std::string("HasKey"), m.Name());
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::PropertyList::HasKey"), m.Name(SCOPED));
  CPPUNIT_ASSERT(!m.IsConstructor());
  CPPUNIT_ASSERT(!m.IsDestructor());

  m = t.FunctionMemberAt(10);
  CPPUNIT_ASSERT(m);
  CPPUNIT_ASSERT_EQUAL(std::string("HasProperty"), m.Name());
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::PropertyList::HasProperty"), m.Name(SCOPED));
  CPPUNIT_ASSERT(!m.IsConstructor());
  CPPUNIT_ASSERT(!m.IsDestructor());

  m = t.FunctionMemberAt(11);
  CPPUNIT_ASSERT(m);
  CPPUNIT_ASSERT_EQUAL(std::string("HasProperty"), m.Name());
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::PropertyList::HasProperty"), m.Name(SCOPED));
  CPPUNIT_ASSERT(!m.IsConstructor());
  CPPUNIT_ASSERT(!m.IsDestructor());

  m = t.FunctionMemberAt(12);
  CPPUNIT_ASSERT(m);
  CPPUNIT_ASSERT_EQUAL(std::string("Key_Begin"), m.Name());
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::PropertyList::Key_Begin"), m.Name(SCOPED));
  CPPUNIT_ASSERT(!m.IsConstructor());
  CPPUNIT_ASSERT(!m.IsDestructor());

  m = t.FunctionMemberAt(13);
  CPPUNIT_ASSERT(m);
  CPPUNIT_ASSERT_EQUAL(std::string("Key_End"), m.Name());
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::PropertyList::Key_End"), m.Name(SCOPED));
  CPPUNIT_ASSERT(!m.IsConstructor());
  CPPUNIT_ASSERT(!m.IsDestructor());

  o.Destruct();
  CPPUNIT_ASSERT(!o);
}

void ReflexSimple1Test::testVirtual() {

  Type t1 = Type::ByName("ROOT::Reflex::Type");
  Type t2 = Type::ByName("ROOT::Reflex::TypeBase");

  CPPUNIT_ASSERT(t1);
  CPPUNIT_ASSERT_EQUAL(std::string("Type"),t1.Name());
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::Type"), t1.Name(SCOPED));
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::Type"), t1.Name(SCOPED|QUALIFIED|FINAL));
  CPPUNIT_ASSERT(!t1.IsVirtual());
  CPPUNIT_ASSERT(t2);
  CPPUNIT_ASSERT_EQUAL(std::string("TypeBase"),t2.Name());
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::TypeBase"), t2.Name(SCOPED));
  CPPUNIT_ASSERT_EQUAL(std::string("ROOT::Reflex::TypeBase"), t2.Name(SCOPED|QUALIFIED|FINAL));
  CPPUNIT_ASSERT(t2.IsVirtual());

}

void ReflexSimple1Test::unloadLibrary() {
#if defined (_WIN32)
  int ret = FreeLibrary(s_libInstance);
  if (ret == 0) std::cout << "Unload of dictionary library failed. Reason: " << GetLastError() << std::endl;
  CPPUNIT_ASSERT(ret);
#else
  int ret = dlclose(s_libInstance);
  if (ret == -1) std::cout << "Unload of dictionary library failed. Reason: " << dlerror() << std::endl;
  CPPUNIT_ASSERT(!ret);
#endif
  //std::cout << "Endless" << std::endl;
  //while (true) {}

}

// Class registration on cppunit framework
CPPUNIT_TEST_SUITE_REGISTRATION(ReflexSimple1Test);

// CppUnit test-driver common for all the cppunit test classes
#include<CppUnit_testdriver.cpp>
<|endoftext|>


<commit_before>#include "classui.h"
#include "listworker.h"
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <time.h>

using namespace std;

ClassUI::ClassUI()
{

}

void ClassUI::run()
{

    cout << "\t" << "Welcome to the Amazing Database! " << endl;
    cout << "-----------------------------------------------------------" << endl;
    cout << "\t" << "   *** Quote of the day ***" << endl;
    cout << getQuotes() << endl;
    mainMenu();
}
void ClassUI::mainMenu()
{
    string choice;
    do
    {

        cout << "-----------------------------------------------------------" << endl;
        cout << " (1) - Add" << "\t" << "Add a person to the database." << endl;
        cout << " (2) - Remove" << "\t" << "Remove a person from the database." << endl;
        cout << " (3) - View" << "\t" << "View the entire database." << endl;
        cout << " (4) - Save" << "\t" << "Save the database." << endl;
        cout << " (5) - Search" << "\t" << "Search the database." << endl;
        cout << " (6) - Sort" << "\t" << "Sort the database." << endl;
        cout << " (7) - Exit" << "\t" << "Exit." << endl;

        cout << "Enter your command (1 - 7): ";
        cin >> choice;
        cout << endl;

        if (choice != "7")
        {
           select(choice);
        }
        else{
            list.saveFile();
            runOn = false;
        }
    }while(runOn == true);
}

void ClassUI::select(string ch)
{
    if(ch == "1")
    {
        addPerson();
    }

    else if(ch == "3")
    {
        viewAll();
    }
    else if(ch == "6")
    {
        string sortcho;
        cout << "Enter a sort command (1 - 3):" << endl;
        cout << "------------------------" << endl;
        cout << " (1) - Sort by alphabetical order" << endl;
        cout << " (2) - Sort by chronological order" << endl;
        cout << " (3) - Return to main menu" << endl;
        cout << "Enter your command (1 - 2): ";
        cin >> sortcho;
        cout << endl;

        if(sortcho == "1")
        {
            list.sortNames();
             viewAll();
        }
        else if(sortcho == "2")
        {
            list.sortBirth();
             viewAll();
        }
        else if(sortcho == "3")
        {
            mainMenu();
        }

    }
    else if(ch == "5")
    {
        searching();
    }
    else if(ch == "2")
    {
        remove();
    }
    else if(ch == "4")
    {
        save();
    }
    else if(ch == "8")
    {
        yo();
    }
    else
    {
        cout << "Invalid input. Please enter a number between 1 - 7." << endl;
    }
}
void ClassUI::view(int i)
{
    int nameSize  = list.getNameSize(i);
    cout << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << "Name" << "\t" << "\t" << "\t" << "\t" << "|Gender " << "|Born " << "\t" << "|Death" << endl;
    cout << "--------------------------------|-------|-------|-------------" << endl;

    cout << list.getName(i);
    if(nameSize > 0 && nameSize <= 7)
    {
        cout << "\t" << "\t" << "\t" << "\t";
    }
    else if(nameSize > 7 && nameSize <= 15)
    {
        cout << "\t" << "\t" << "\t";
    }
    else if(nameSize > 15 && nameSize <= 23)
    {
        cout << "\t" << "\t";
    }
    else if(nameSize > 23 && nameSize <= 31)
    {
        cout << "\t";
    }

    if(list.getGender(i) == 'M' || list.getGender(i) == 'm')
    {
        cout << "|Male" << "\t";
    }
    else
    {
        cout << "|Female" << "\t";
    }
    cout  << "|" << list.getBirth(i);
    if(list.getDeath(i) == 0)
    {
        cout << "\t" << "| n/a"  << endl;
    }
    else
    {
        cout << "\t" << "|" << list.getDeath(i)  << endl;
    }
    cout << list.getComment(i) << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << endl;
}

void ClassUI::searching()
{

    cout << "----------Select any of the following commands----------" << endl;
    cout << "What do you want to search for? (1 - 4)" << endl;
    cout << " (1) - Searches for a name." << endl;
    cout << " (2) - Searches for a Gender." << endl;
    cout << " (3) - Searches for a year born." << endl;
    cout << " (4) - Return to main menu" << endl;

    search();
}
void ClassUI::addPerson()
{
    string name;
    char gender;
    char yesOrNo;
    int yearOfBirth = 0;
    int yearOfDeath = 0;
    string comment;

    cout << "Input Name: ";
    cin.ignore();
    std::getline(std::cin,name);
    cout << "Input gender (M/F): ";
    cin >> gender;
    if (gender == 'm')
    {
        gender = 'M';
    }
    else if (gender == 'f')
    {
        gender = 'F';
    }
    if (gender == 'm' || gender == 'M' || gender == 'f' || gender == 'F')
    {
       cout << "Input year of birth: ";
       cin >> yearOfBirth;

       cout << "Is the individual deceased? (y/n)";
       cin >> yesOrNo;
       if (yesOrNo == 'Y' || yesOrNo == 'y')
       {
            cout << "Input year of death: ";
            cin >> yearOfDeath;
       }
        cout << "Input a comment about the individual: ";
        cin.ignore();
        std::getline(std::cin,comment);
    }
    else
    {
        cout << "Invalid gender! Try again." << endl;
        addPerson();
    }
    cout << "Are you sure that you want to add this person? yes or no: "; // Þetta er ógeðslegur texti, endilega finnum eitthvað skárra
    string validatePerson;
    cin >> validatePerson;
    if(validatePerson == "yes")
    {
        cout << "New person added!" << endl;
        list.addNewPerson(name, gender, yearOfBirth, yearOfDeath, comment);
    }
    else
    {
        cout << "Operation addPerson aborted!" << endl; // Endilega komið með tillögu að breytingu á þessum texta
    }
}

void ClassUI::search()
{
    string searchChoice;
    cout << "Enter your command (1 - 4): ";
    cin >> searchChoice;
    if (searchChoice == "1")
    {

        string namesearch;
        cout << "Enter a name you want to search for: ";
        cin.ignore();
        std::getline(std::cin,namesearch);

        for(int i = 0; i < list.getPersonsSize();++i)
        {
            std::size_t found = list.getName(i).find(namesearch);
            if (found!=std::string::npos)
            {
                view(i);
            }

        }
        if(list.nameSearcher(namesearch) == false)
        {
            cout << "Sorry that name is not in our database, but you can add a new instance in the 'Add' section in the main menu." << endl;
            searching();
        }
    }
    else if (searchChoice == "2")
    {
        char gendersearch;

        cout << "Enter a gender you want to search for: (M/F)";
        cin >> gendersearch;
        if(gendersearch == 'm')
            {
                 gendersearch = 'M';
            }
        else if (gendersearch == 'f')
            {
                 gendersearch = 'F';
            }

        for(int i = 0; i < list.getPersonsSize();++i)
        {
            if(gendersearch == list.getGender(i))
            {
                gendersearch = list.getGender(i);
                view(i);
            }
        }
        if(list.genderSearcher(gendersearch) == false)
        {
            cout << "Sorry that gender is not in our database, but you can add a new instance in the 'Add' section in the main menu." << endl;
            searching();
        }
    }
    else if (searchChoice == "3")
    {
            int yearsearch;
            cout << "Enter a year you want to search for: ";
            cin >> yearsearch;

            for(int i = 0; i < list.getPersonsSize();++i)
            {
                if(yearsearch == list.getBirth(i))
                {
                    yearsearch = list.getBirth(i);
                    view(i);
                }
            }
            if(list.yearSearcher(yearsearch) == false)
            {
                cout << "Sorry that year is not in our database, but you can add a new instance in the 'Add' section in the main menu." << endl;
                searching();
            }
    }
    else if (searchChoice == "4")
    {
        mainMenu();
    }
    else
    {
        cout << "Error reading input. Please enter a number between 1- 3." << endl;
        search();
    }
}
void ClassUI::remove()
{
    string name;
    cout << "Enter the full name of the person that you want to remove: ";
    cin.ignore();
    std::getline(std::cin,name);
    if (list.removePersonFound(name) == true)
    {
        char validateRemove;
        cout << "Person found!" << endl;
        cout << "Are you sure you want to remove this person? (y/n): ";
        cin >> validateRemove;

        if(validateRemove == 'y' || validateRemove == 'Y')
        {
            if(list.removePerson(name) == true)
            {
                cout << "Person removed!" << endl;
            }
            else
            {
                cout << "Person not removed!" << endl;
            }
        }

    }
    else
    {
        cout << "Person not found!" << endl;
    }
}
void ClassUI::save()
{
    list.saveFile();
}
void ClassUI::viewAll()
{
    for(int i = 0; i < list.getPersonsSize(); i++)
    {
        view(i);
    }
}
void ClassUI::yo()
{
    cout << endl;
    cout << "`8.`8888.      ,8'     ,o888888o.     " << endl;
    cout << " `8.`8888.    ,8'   . 8888     `88.   " << endl;
    cout << "  `8.`8888.  ,8'   ,8 8888       `8b  " << endl;
    cout << "   `8.`8888.,8'    88 8888        `8b " << endl;
    cout << "    `8.`88888'     88 8888         88 " << endl;
    cout << "     `8. 8888      88 8888         88 " << endl;
    cout << "      `8 8888      88 8888        ,8P " << endl;
    cout << "       8 8888      `8 8888       ,8P  " << endl;
    cout << "       8 8888       ` 8888     ,88'   " << endl;
    cout << "       8 8888          `8888888P'     " << endl;
    cout << endl;
}

string ClassUI::getQuotes()
{
    string quotes[5] = {"\"A good programmer is someone who always looks both ways before crossing a one-way street.\" (Doug Linder)",
                        "\"Programming is like sex. One mistake and you have to support it for the rest of your life.\" (Michael Sinz)",
                        "\"Walking on water and developing software from a specification are easy if both are frozen.\" (Edward V Berard)",
                        "\"One man's crappy software is another man's full time job.\" (Jessica Gaston)",
                        "\"A C program is like a fast dance on a newly waxed dance floor by people carrying razors.\" (Waldi Ravens)"
                       };
    int v1 = 0;
    srand (time(NULL));
    v1 = rand() % 5;
    return quotes[v1];
}
<commit_msg>smá lagfæringar á ClassUI<commit_after>#include "classui.h"
#include "listworker.h"
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <time.h>

using namespace std;

ClassUI::ClassUI()
{

}

void ClassUI::run()
{

    cout << "\t" << "Welcome to the Amazing Database! " << endl;
    cout << "-----------------------------------------------------------" << endl;
    cout << "\t" << "   *** Quote of the day ***" << endl;
    cout << getQuotes() << endl;
    mainMenu();
}
void ClassUI::mainMenu()
{
    string choice;
    do
    {

        cout << "-----------------------------------------------------------" << endl;
        cout << " (1) - " << "\t" << "Add a person to the database." << endl;
        cout << " (2) - " << "\t" << "Remove a person from the database." << endl;
        cout << " (3) - " << "\t" << "View the entire database." << endl;
        cout << " (4) - " << "\t" << "Save the database." << endl;
        cout << " (5) - " << "\t" << "Search the database." << endl;
        cout << " (6) - " << "\t" << "Sort the database." << endl;
        cout << " (7) - " << "\t" << "Exit." << endl;

        cout << "Enter your command (1 - 7): ";
        cin >> choice;
        cout << endl;

        if (choice != "7")
        {
           select(choice);
        }
        else{
            list.saveFile();
            runOn = false;
        }
    }while(runOn == true);
}

void ClassUI::select(string ch)
{
    if(ch == "1")
    {
        addPerson();
    }

    else if(ch == "3")
    {
        viewAll();
    }
    else if(ch == "6")
    {
        string sortcho;
        cout << "Enter a sort command (1 - 3):" << endl;
        cout << "------------------------" << endl;
        cout << " (1) - Sort by alphabetical order" << endl;
        cout << " (2) - Sort by chronological order" << endl;
        cout << " (3) - Return to main menu" << endl;
        cout << "Enter your command (1 - 2): ";
        cin >> sortcho;
        cout << endl;

        if(sortcho == "1")
        {
            list.sortNames();
             viewAll();
        }
        else if(sortcho == "2")
        {
            list.sortBirth();
             viewAll();
        }
        else if(sortcho == "3")
        {
            mainMenu();
        }

    }
    else if(ch == "5")
    {
        searching();
    }
    else if(ch == "2")
    {
        remove();
    }
    else if(ch == "4")
    {
        save();
    }
    else if(ch == "8")
    {
        yo();
    }
    else
    {
        cout << "Invalid input. Please enter a number between 1 - 7." << endl;
    }
}
void ClassUI::view(int i)
{
    int nameSize  = list.getNameSize(i);
    cout << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << "Name" << "\t" << "\t" << "\t" << "\t" << "|Gender " << "|Born " << "\t" << "|Death" << endl;
    cout << "--------------------------------|-------|-------|-------------" << endl;

    cout << list.getName(i);
    if(nameSize > 0 && nameSize <= 7)
    {
        cout << "\t" << "\t" << "\t" << "\t";
    }
    else if(nameSize > 7 && nameSize <= 15)
    {
        cout << "\t" << "\t" << "\t";
    }
    else if(nameSize > 15 && nameSize <= 23)
    {
        cout << "\t" << "\t";
    }
    else if(nameSize > 23 && nameSize <= 31)
    {
        cout << "\t";
    }

    if(list.getGender(i) == 'M' || list.getGender(i) == 'm')
    {
        cout << "|Male" << "\t";
    }
    else
    {
        cout << "|Female" << "\t";
    }
    cout  << "|" << list.getBirth(i);
    if(list.getDeath(i) == 0)
    {
        cout << "\t" << "| n/a"  << endl;
    }
    else
    {
        cout << "\t" << "|" << list.getDeath(i)  << endl;
    }
    cout << list.getComment(i) << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << endl;
}

void ClassUI::searching()
{

    cout << "----------Select any of the following commands----------" << endl;
    cout << "What do you want to search for? (1 - 4)" << endl;
    cout << " (1) - Searches for a name." << endl;
    cout << " (2) - Searches for a Gender." << endl;
    cout << " (3) - Searches for a year born." << endl;
    cout << " (4) - Return to main menu" << endl;

    search();
}
void ClassUI::addPerson()
{
    string name;
    char gender;
    char yesOrNo;
    int yearOfBirth = 0;
    int yearOfDeath = 0;
    string comment;

    cout << "Input Name: ";
    cin.ignore();
    std::getline(std::cin,name);
    cout << "Input gender (M/F): ";
    cin >> gender;
    if (gender == 'm')
    {
        gender = 'M';
    }
    else if (gender == 'f')
    {
        gender = 'F';
    }
    if (gender == 'm' || gender == 'M' || gender == 'f' || gender == 'F')
    {
       cout << "Input year of birth: ";
       cin >> yearOfBirth;

       cout << "Is the individual deceased? (y/n)";
       cin >> yesOrNo;
       if (yesOrNo == 'Y' || yesOrNo == 'y')
       {
            cout << "Input year of death: ";
            cin >> yearOfDeath;
       }
        cout << "Input a comment about the individual: ";
        cin.ignore();
        std::getline(std::cin,comment);
    }
    else
    {
        cout << "Invalid gender! Try again." << endl;
        addPerson();
    }
    cout << "Are you sure that you want to add this person? yes or no: "; // Þetta er ógeðslegur texti, endilega finnum eitthvað skárra
    string validatePerson;
    cin >> validatePerson;
    if(validatePerson == "yes")
    {
        cout << "New person added!" << endl;
        list.addNewPerson(name, gender, yearOfBirth, yearOfDeath, comment);
    }
    else
    {
        cout << "Operation addPerson aborted!" << endl; // Endilega komið með tillögu að breytingu á þessum texta
    }
}

void ClassUI::search()
{
    string searchChoice;
    cout << "Enter your command (1 - 4): ";
    cin >> searchChoice;
    cout << endl;
    if (searchChoice == "1")
    {

        string namesearch;
        cout << "Enter a name you want to search for: ";
        cin.ignore();
        std::getline(std::cin,namesearch);

        for(int i = 0; i < list.getPersonsSize();++i)
        {
            std::size_t found = list.getName(i).find(namesearch);
            if (found!=std::string::npos)
            {
                view(i);
            }

        }
        if(list.nameSearcher(namesearch) == false)
        {
            cout << "Sorry that name is not in our database, but you can add a new instance in the 'Add' section in the main menu." << endl;
            searching();
        }
    }
    else if (searchChoice == "2")
    {
        char gendersearch;

        cout << "Enter a gender you want to search for: (M/F)";
        cin >> gendersearch;
        if(gendersearch == 'm')
            {
                 gendersearch = 'M';
            }
        else if (gendersearch == 'f')
            {
                 gendersearch = 'F';
            }

        for(int i = 0; i < list.getPersonsSize();++i)
        {
            if(gendersearch == list.getGender(i))
            {
                gendersearch = list.getGender(i);
                view(i);
            }
        }
        if(list.genderSearcher(gendersearch) == false)
        {
            cout << "Sorry that gender is not in our database, but you can add a new instance in the 'Add' section in the main menu." << endl;
            searching();
        }
    }
    else if (searchChoice == "3")
    {
            int yearsearch;
            cout << "Enter a year you want to search for: ";
            cin >> yearsearch;

            for(int i = 0; i < list.getPersonsSize();++i)
            {
                if(yearsearch == list.getBirth(i))
                {
                    yearsearch = list.getBirth(i);
                    view(i);
                }
            }
            if(list.yearSearcher(yearsearch) == false)
            {
                cout << "Sorry that year is not in our database, but you can add a new instance in the 'Add' section in the main menu." << endl;
                searching();
            }
    }
    else if (searchChoice == "4")
    {
        mainMenu();
    }
    else
    {
        cout << "Error reading input. Please enter a number between 1- 3." << endl;
        search();
    }
}
void ClassUI::remove()
{
    string name;
    cout << "Enter the full name of the person that you want to remove: ";
    cin.ignore();
    std::getline(std::cin,name);
    if (list.removePersonFound(name) == true)
    {
        char validateRemove;
        cout << "Person found!" << endl;
        cout << "Are you sure you want to remove this person? (y/n): ";
        cin >> validateRemove;

        if(validateRemove == 'y' || validateRemove == 'Y')
        {
            if(list.removePerson(name) == true)
            {
                cout << "Person removed!" << endl;
            }
            else
            {
                cout << "Person not removed!" << endl;
            }
        }

    }
    else
    {
        cout << "Person not found!" << endl;
    }
}
void ClassUI::save()
{
    list.saveFile();
}
void ClassUI::viewAll()
{
    for(int i = 0; i < list.getPersonsSize(); i++)
    {
        view(i);
    }
}
void ClassUI::yo()
{
    cout << endl;
    cout << "`8.`8888.      ,8'     ,o888888o.     " << endl;
    cout << " `8.`8888.    ,8'   . 8888     `88.   " << endl;
    cout << "  `8.`8888.  ,8'   ,8 8888       `8b  " << endl;
    cout << "   `8.`8888.,8'    88 8888        `8b " << endl;
    cout << "    `8.`88888'     88 8888         88 " << endl;
    cout << "     `8. 8888      88 8888         88 " << endl;
    cout << "      `8 8888      88 8888        ,8P " << endl;
    cout << "       8 8888      `8 8888       ,8P  " << endl;
    cout << "       8 8888       ` 8888     ,88'   " << endl;
    cout << "       8 8888          `8888888P'     " << endl;
    cout << endl;
}

string ClassUI::getQuotes()
{
    string quotes[5] = {"\"A good programmer is someone who always looks both ways before crossing a one-way street.\" (Doug Linder)",
                        "\"Programming is like sex. One mistake and you have to support it for the rest of your life.\" (Michael Sinz)",
                        "\"Walking on water and developing software from a specification are easy if both are frozen.\" (Edward V Berard)",
                        "\"One man's crappy software is another man's full time job.\" (Jessica Gaston)",
                        "\"A C program is like a fast dance on a newly waxed dance floor by people carrying razors.\" (Waldi Ravens)"
                       };
    int v1 = 0;
    srand (time(NULL));
    v1 = rand() % 5;
    return quotes[v1];
}
<|endoftext|>


<commit_before>#include "medViewerConfigurationRegistration.h"

#include <dtkCore/dtkAbstractViewFactory.h>
#include <dtkCore/dtkAbstractView.h>

#include <medViewerToolBoxViewProperties.h>
#include <medToolBoxRegistration.h>
#include <medViewContainer.h>
#include <medViewContainerSingle.h>
#include <medViewContainerCompare.h>
#include <medTabbedViewContainers.h>
#include <medToolBoxRegistration.h>

class medViewerConfigurationRegistrationPrivate
{
public:
    medToolBoxRegistration * registrationToolBox;
    medViewerToolBoxViewProperties      *viewPropertiesToolBox;
};

medViewerConfigurationRegistration::medViewerConfigurationRegistration(QWidget *parent) : medViewerConfiguration(parent), d(new medViewerConfigurationRegistrationPrivate)
{

    d->viewPropertiesToolBox = new medViewerToolBoxViewProperties(parent);
    this->addToolBox(d->viewPropertiesToolBox);

    // -- Registration toolbox --

    d->registrationToolBox = new medToolBoxRegistration(parent);

    connect(d->registrationToolBox, SIGNAL(setupLayoutCompare()), this, SLOT(onSetupLayoutCompare()));
    connect(d->registrationToolBox, SIGNAL(setupLayoutFuse()),    this, SLOT(onSetupLayoutFuse()));

    connect(d->registrationToolBox, SIGNAL(addToolBox(medToolBox *)),
            this, SLOT(addToolBox(medToolBox *)));
    connect(d->registrationToolBox, SIGNAL(removeToolBox(medToolBox *)),
            this, SLOT(removeToolBox(medToolBox *)));

    this->addToolBox( d->registrationToolBox );

    //this->setLayoutType(medViewerConfiguration::TopDbBottomTb);
    this->setLayoutType(medViewerConfiguration::LeftDbRightTb);
}

medViewerConfigurationRegistration::~medViewerConfigurationRegistration(void)
{
    delete d;
    d = NULL;
}

QString medViewerConfigurationRegistration::identifier() const {
    return "Registration";
}

QString medViewerConfigurationRegistration::description() const {
    return "Registration";
}

void medViewerConfigurationRegistration::setupViewContainerStack()
{
    //the stack has been instantiated in constructor
    if (!this->stackedViewContainers()->count())
    {
        //create the fuse container
        medViewContainerSingle *fuseContainer = new medViewContainerSingle(
                this->stackedViewContainers());
        if (dtkAbstractView *view = dtkAbstractViewFactory::instance()->create("v3dView"))
        {
            fuseContainer->setView (view);
            d->registrationToolBox->setFuseView (view);
        }

        //create the compare container
        medViewContainerCompare * compareContainer = new medViewContainerCompare(
                this->stackedViewContainers());
        connect(compareContainer,SIGNAL(droppedFixed(medDataIndex)),
                d->registrationToolBox,SLOT(onFixedImageDropped(medDataIndex)));
        connect(compareContainer,SIGNAL(droppedMoving(medDataIndex)),
                d->registrationToolBox,SLOT(onMovingImageDropped(medDataIndex)));

        this->stackedViewContainers()->addContainer("Compare",compareContainer);
        this->stackedViewContainers()->addContainer("Fuse",fuseContainer);
        this->stackedViewContainers()->lockTabs();
        setCurrentViewContainer("Compare");
    }
}

void medViewerConfigurationRegistration::patientChanged(int patientId)
{
    d->registrationToolBox->clear();
}

medViewerConfiguration *createMedViewerConfigurationRegistration(QWidget* parent)
{
    return new medViewerConfigurationRegistration(parent);
}

<commit_msg>Removed dangling connections<commit_after>#include "medViewerConfigurationRegistration.h"

#include <dtkCore/dtkAbstractViewFactory.h>
#include <dtkCore/dtkAbstractView.h>

#include <medViewerToolBoxViewProperties.h>
#include <medToolBoxRegistration.h>
#include <medViewContainer.h>
#include <medViewContainerSingle.h>
#include <medViewContainerCompare.h>
#include <medTabbedViewContainers.h>
#include <medToolBoxRegistration.h>

class medViewerConfigurationRegistrationPrivate
{
public:
    medToolBoxRegistration * registrationToolBox;
    medViewerToolBoxViewProperties      *viewPropertiesToolBox;
};

medViewerConfigurationRegistration::medViewerConfigurationRegistration(QWidget *parent) : medViewerConfiguration(parent), d(new medViewerConfigurationRegistrationPrivate)
{

    d->viewPropertiesToolBox = new medViewerToolBoxViewProperties(parent);
    this->addToolBox(d->viewPropertiesToolBox);

    // -- Registration toolbox --

    d->registrationToolBox = new medToolBoxRegistration(parent);

    connect(d->registrationToolBox, SIGNAL(addToolBox(medToolBox *)),
            this, SLOT(addToolBox(medToolBox *)));
    connect(d->registrationToolBox, SIGNAL(removeToolBox(medToolBox *)),
            this, SLOT(removeToolBox(medToolBox *)));

    this->addToolBox( d->registrationToolBox );

    //this->setLayoutType(medViewerConfiguration::TopDbBottomTb);
    this->setLayoutType(medViewerConfiguration::LeftDbRightTb);
}

medViewerConfigurationRegistration::~medViewerConfigurationRegistration(void)
{
    delete d;
    d = NULL;
}

QString medViewerConfigurationRegistration::identifier() const {
    return "Registration";
}

QString medViewerConfigurationRegistration::description() const {
    return "Registration";
}

void medViewerConfigurationRegistration::setupViewContainerStack()
{
    //the stack has been instantiated in constructor
    if (!this->stackedViewContainers()->count())
    {
        //create the fuse container
        medViewContainerSingle *fuseContainer = new medViewContainerSingle(
                this->stackedViewContainers());
        if (dtkAbstractView *view = dtkAbstractViewFactory::instance()->create("v3dView"))
        {
            fuseContainer->setView (view);
            d->registrationToolBox->setFuseView (view);
        }

        //create the compare container
        medViewContainerCompare * compareContainer = new medViewContainerCompare(
                this->stackedViewContainers());
        connect(compareContainer,SIGNAL(droppedFixed(medDataIndex)),
                d->registrationToolBox,SLOT(onFixedImageDropped(medDataIndex)));
        connect(compareContainer,SIGNAL(droppedMoving(medDataIndex)),
                d->registrationToolBox,SLOT(onMovingImageDropped(medDataIndex)));

        this->stackedViewContainers()->addContainer("Compare",compareContainer);
        this->stackedViewContainers()->addContainer("Fuse",fuseContainer);
        this->stackedViewContainers()->lockTabs();
        setCurrentViewContainer("Compare");
    }
}

void medViewerConfigurationRegistration::patientChanged(int patientId)
{
    d->registrationToolBox->clear();
}

medViewerConfiguration *createMedViewerConfigurationRegistration(QWidget* parent)
{
    return new medViewerConfigurationRegistration(parent);
}

<|endoftext|>


<commit_before>/*
 * This file is part of telepathy-accounts-kcm
 *
 * Copyright (C) 2009 Collabora Ltd. <http://www.collabora.co.uk/>
 * Copyright (C) 2011 Thomas Richard <thomas.richard@proan.be>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "profile-select-widget.h"

#include "profile-item.h"
#include "profile-list-model.h"

#include "ui_profile-select-widget.h"

#include <KDebug>

#include <TelepathyQt4/PendingReady>
#include <TelepathyQt4/ProfileManager>
#include <TelepathyQt4/Feature>

class ProfileSelectWidget::Private
{
public:
    Private()
     : profileManager(0),
       ui(0),
       model(0)
    {
        kDebug();
    }

    Tp::ProfileManagerPtr profileManager;
    Ui::ProfileSelectWidget *ui;
    ProfileListModel *model;
};

ProfileSelectWidget::ProfileSelectWidget(QWidget *parent)
 : QWidget(parent),
   d(new Private)
{
    kDebug();

    // Set up the widget
    d->model = new ProfileListModel(this);

    d->ui = new Ui::ProfileSelectWidget;
    d->ui->setupUi(this);
    d->ui->profileListView->setModel(d->model);

    connect(d->ui->profileListView->selectionModel(),
            SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)),
            SLOT(onSelectionChanged(const QItemSelection &)));
    connect(d->ui->profileListView,
            SIGNAL(doubleClicked(QModelIndex)),
            SIGNAL(profileDoubleClicked()));

    d->profileManager = Tp::ProfileManager::create(QDBusConnection::sessionBus());

    // FIXME: Until all distros ship correct profile files, we should fake them
    connect(d->profileManager->becomeReady(Tp::Features() << Tp::ProfileManager::FeatureFakeProfiles),
            SIGNAL(finished(Tp::PendingOperation*)),
            SLOT(onProfileManagerReady(Tp::PendingOperation*)));
}

ProfileSelectWidget::~ProfileSelectWidget()
{
    kDebug();

    delete d->ui;
    delete d;
}

void ProfileSelectWidget::onProfileManagerReady(Tp::PendingOperation *op)
{
    kDebug();

    // Check the pending operation completed successfully.
    if (op->isError()) {
        kDebug() << "becomeReady() failed:" << op->errorName() << op->errorMessage();
        return;
    }

    d->model->setProfileManager(d->profileManager);
}

// Return the selected ProfileItem or 0 if nothing is selected.
ProfileItem *ProfileSelectWidget::selectedProfile()
{
    kDebug();

    // Get the indexes of the selected items from the view
    QModelIndexList selectedIndexes = d->ui->profileListView->selectionModel()->selectedIndexes();

    // If more than 1 profile is selected (shouldn't be possible, but just in case) error.
    if (selectedIndexes.size() > 1) {
        kWarning() << "More than 1 profile is selected.";
        return 0;
    }

    // If no indexes are selected, return 0.
    if (selectedIndexes.size() == 0) {
        return 0;
    }

    // 1 index is selected. Return the Pr for that.
    return d->model->itemForIndex(selectedIndexes.at(0));
}

void ProfileSelectWidget::onSelectionChanged(const QItemSelection &selected)
{
    kDebug();

    Q_EMIT profileGotSelected(!selected.isEmpty());
}

#include "profile-select-widget.moc"

<commit_msg>Sort profile list alphabetically.<commit_after>/*
 * This file is part of telepathy-accounts-kcm
 *
 * Copyright (C) 2009 Collabora Ltd. <http://www.collabora.co.uk/>
 * Copyright (C) 2011 Thomas Richard <thomas.richard@proan.be>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "profile-select-widget.h"

#include "profile-item.h"
#include "profile-list-model.h"

#include "ui_profile-select-widget.h"

#include <KDebug>

#include <TelepathyQt4/PendingReady>
#include <TelepathyQt4/ProfileManager>
#include <TelepathyQt4/Feature>

#include <QSortFilterProxyModel>
#include <qitemselectionmodel.h>

class ProfileSelectWidget::Private
{
public:
    Private()
     : profileManager(0),
       ui(0),
       sourceModel(0),
       sortModel(0)
    {
        kDebug();
    }

    Tp::ProfileManagerPtr profileManager;
    Ui::ProfileSelectWidget *ui;
    QSortFilterProxyModel *sortModel;
    ProfileListModel *sourceModel;
};

ProfileSelectWidget::ProfileSelectWidget(QWidget *parent)
 : QWidget(parent),
   d(new Private)
{
    kDebug();

    // Set up the models
    d->sourceModel = new ProfileListModel(this);
    d->sortModel = new QSortFilterProxyModel(this);
    d->sortModel->setSourceModel(d->sourceModel);
    d->sortModel->sort(0, Qt::AscendingOrder);
    d->sortModel->setDynamicSortFilter(true);
    d->sortModel->setSortCaseSensitivity(Qt::CaseInsensitive);

    // Set up the widget
    d->ui = new Ui::ProfileSelectWidget;
    d->ui->setupUi(this);
    d->ui->profileListView->setModel(d->sortModel);

    connect(d->ui->profileListView->selectionModel(),
            SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)),
            SLOT(onSelectionChanged(const QItemSelection &)));
    connect(d->ui->profileListView,
            SIGNAL(doubleClicked(QModelIndex)),
            SIGNAL(profileDoubleClicked()));

    d->profileManager = Tp::ProfileManager::create(QDBusConnection::sessionBus());

    // FIXME: Until all distros ship correct profile files, we should fake them
    connect(d->profileManager->becomeReady(Tp::Features() << Tp::ProfileManager::FeatureFakeProfiles),
            SIGNAL(finished(Tp::PendingOperation*)),
            SLOT(onProfileManagerReady(Tp::PendingOperation*)));
}

ProfileSelectWidget::~ProfileSelectWidget()
{
    kDebug();

    delete d->ui;
    delete d;
}

void ProfileSelectWidget::onProfileManagerReady(Tp::PendingOperation *op)
{
    kDebug();

    // Check the pending operation completed successfully.
    if (op->isError()) {
        kDebug() << "becomeReady() failed:" << op->errorName() << op->errorMessage();
        return;
    }

    d->sourceModel->setProfileManager(d->profileManager);
}

// Return the selected ProfileItem or 0 if nothing is selected.
ProfileItem *ProfileSelectWidget::selectedProfile()
{
    kDebug();

    // Get the indexes of the selected items from the view
    QModelIndexList selectedIndexes = d->ui->profileListView->selectionModel()->selectedIndexes();

    // If more than 1 profile is selected (shouldn't be possible, but just in case) error.
    if (selectedIndexes.size() > 1) {
        kWarning() << "More than 1 profile is selected.";
        return 0;
    }

    // If no indexes are selected, return 0.
    if (selectedIndexes.size() == 0) {
        return 0;
    }

    // 1 index is selected. Return the Pr for that.
    QItemSelection sourceSelection = d->sortModel->mapSelectionToSource(d->ui->profileListView->selectionModel()->selection());

    return d->sourceModel->itemForIndex(sourceSelection.indexes().first());
}

void ProfileSelectWidget::onSelectionChanged(const QItemSelection &selected)
{
    kDebug();

    Q_EMIT profileGotSelected(!selected.isEmpty());
}

#include "profile-select-widget.moc"

<|endoftext|>


<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2014 Torus Knot Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/

#include "OgreGLGpuProgram.h"
#include "OgreException.h"
#include "OgreStringConverter.h"
#include "OgreLogManager.h"
#include "OgreGLSLProgramCommon.h"

namespace Ogre {

GLenum GLArbGpuProgram::getProgramType() const
{
    switch (mType)
    {
        case GPT_VERTEX_PROGRAM:
        default:
            return GL_VERTEX_PROGRAM_ARB;
        case GPT_GEOMETRY_PROGRAM:
            return GL_GEOMETRY_PROGRAM_NV;
        case GPT_FRAGMENT_PROGRAM:
            return GL_FRAGMENT_PROGRAM_ARB;
    }
}

GLGpuProgram::GLGpuProgram(ResourceManager* creator, const String& name,
    ResourceHandle handle, const String& group, bool isManual,
    ManualResourceLoader* loader)
    : GpuProgram(creator, name, handle, group, isManual, loader)
{
    if (createParamDictionary("GLGpuProgram"))
    {
        setupBaseParamDictionary();
    }
}

GLGpuProgram::~GLGpuProgram()
{
    // have to call this here reather than in Resource destructor
    // since calling virtual methods in base destructors causes crash
    unload();
}

bool GLGpuProgram::isAttributeValid(VertexElementSemantic semantic, uint index)
{
    // default implementation
    switch(semantic)
    {
        case VES_POSITION:
        case VES_NORMAL:
        case VES_DIFFUSE:
        case VES_SPECULAR:
        case VES_TEXTURE_COORDINATES:
            return false;
        case VES_BLEND_WEIGHTS:
        case VES_BLEND_INDICES:
        case VES_BINORMAL:
        case VES_TANGENT:
            return true; // with default binding
    }

    return false;
}

//-----------------------------------------------------------------------------
size_t GLGpuProgram::calculateSize(void) const
{
    size_t memSize = 0;

    // Delegate Names
    memSize += sizeof(GLuint);
    memSize += sizeof(GLenum);
    memSize += GpuProgram::calculateSize();

    return memSize;
}

GLArbGpuProgram::GLArbGpuProgram(ResourceManager* creator, const String& name,
    ResourceHandle handle, const String& group, bool isManual,
    ManualResourceLoader* loader)
    : GLGpuProgram(creator, name, handle, group, isManual, loader)
{
    glGenProgramsARB(1, &mProgramID);
}

GLArbGpuProgram::~GLArbGpuProgram()
{
    // have to call this here reather than in Resource destructor
    // since calling virtual methods in base destructors causes crash
    unload();
}

void GLArbGpuProgram::bindProgram(void)
{
    glEnable(getProgramType());
    glBindProgramARB(getProgramType(), mProgramID);
}

void GLArbGpuProgram::unbindProgram(void)
{
    glBindProgramARB(getProgramType(), 0);
    glDisable(getProgramType());
}

void GLArbGpuProgram::bindProgramParameters(GpuProgramParametersSharedPtr params, uint16 mask)
{
    GLenum type = getProgramType();

    // only supports float constants
    GpuLogicalBufferStructPtr floatStruct = params->getFloatLogicalBufferStruct();

    for (GpuLogicalIndexUseMap::const_iterator i = floatStruct->map.begin();
        i != floatStruct->map.end(); ++i)
    {
        if (i->second.variability & mask)
        {
            GLuint logicalIndex = static_cast<GLuint>(i->first);
            const float* pFloat = params->getFloatPointer(i->second.physicalIndex);
            // Iterate over the params, set in 4-float chunks (low-level)
            for (size_t j = 0; j < i->second.currentSize; j+=4)
            {
                glProgramLocalParameter4fvARB(type, logicalIndex, pFloat);
                pFloat += 4;
                ++logicalIndex;
            }
        }
    }
}

void GLArbGpuProgram::bindProgramPassIterationParameters(GpuProgramParametersSharedPtr params)
{
    if (params->hasPassIterationNumber())
    {
        GLenum type = getProgramType();

        size_t physicalIndex = params->getPassIterationNumberIndex();
        size_t logicalIndex = params->getFloatLogicalIndexForPhysicalIndex(physicalIndex);
        const float* pFloat = params->getFloatPointer(physicalIndex);
        glProgramLocalParameter4fvARB(type, (GLuint)logicalIndex, pFloat);
    }

}

void GLArbGpuProgram::unloadImpl(void)
{
    glDeleteProgramsARB(1, &mProgramID);
}

void GLArbGpuProgram::loadFromSource(void)
{
    if (GL_INVALID_OPERATION == glGetError()) {
        LogManager::getSingleton().logMessage("Invalid Operation before loading program "+mName, LML_CRITICAL);

    }
    glBindProgramARB(getProgramType(), mProgramID);
    glProgramStringARB(getProgramType(), GL_PROGRAM_FORMAT_ASCII_ARB, (GLsizei)mSource.length(), mSource.c_str());

    if (GL_INVALID_OPERATION == glGetError())
    {
        GLint errPos;
        glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &errPos);
        String errPosStr = StringConverter::toString(errPos);
        const char* errStr = (const char*)glGetString(GL_PROGRAM_ERROR_STRING_ARB);
        // XXX New exception code?
        OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR,
            "Cannot load GL vertex program " + mName +
            ".  Line " + errPosStr + ":\n" + errStr, mName);
    }
    glBindProgramARB(getProgramType(), 0);
}

}
<commit_msg>GL: fix GLArbGpuProgram::loadFromSource exception code & message<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2014 Torus Knot Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/

#include "OgreGLGpuProgram.h"
#include "OgreException.h"
#include "OgreStringConverter.h"
#include "OgreLogManager.h"
#include "OgreGLSLProgramCommon.h"

namespace Ogre {

GLenum GLArbGpuProgram::getProgramType() const
{
    switch (mType)
    {
        case GPT_VERTEX_PROGRAM:
        default:
            return GL_VERTEX_PROGRAM_ARB;
        case GPT_GEOMETRY_PROGRAM:
            return GL_GEOMETRY_PROGRAM_NV;
        case GPT_FRAGMENT_PROGRAM:
            return GL_FRAGMENT_PROGRAM_ARB;
    }
}

GLGpuProgram::GLGpuProgram(ResourceManager* creator, const String& name,
    ResourceHandle handle, const String& group, bool isManual,
    ManualResourceLoader* loader)
    : GpuProgram(creator, name, handle, group, isManual, loader)
{
    if (createParamDictionary("GLGpuProgram"))
    {
        setupBaseParamDictionary();
    }
}

GLGpuProgram::~GLGpuProgram()
{
    // have to call this here reather than in Resource destructor
    // since calling virtual methods in base destructors causes crash
    unload();
}

bool GLGpuProgram::isAttributeValid(VertexElementSemantic semantic, uint index)
{
    // default implementation
    switch(semantic)
    {
        case VES_POSITION:
        case VES_NORMAL:
        case VES_DIFFUSE:
        case VES_SPECULAR:
        case VES_TEXTURE_COORDINATES:
            return false;
        case VES_BLEND_WEIGHTS:
        case VES_BLEND_INDICES:
        case VES_BINORMAL:
        case VES_TANGENT:
            return true; // with default binding
    }

    return false;
}

//-----------------------------------------------------------------------------
size_t GLGpuProgram::calculateSize(void) const
{
    size_t memSize = 0;

    // Delegate Names
    memSize += sizeof(GLuint);
    memSize += sizeof(GLenum);
    memSize += GpuProgram::calculateSize();

    return memSize;
}

GLArbGpuProgram::GLArbGpuProgram(ResourceManager* creator, const String& name,
    ResourceHandle handle, const String& group, bool isManual,
    ManualResourceLoader* loader)
    : GLGpuProgram(creator, name, handle, group, isManual, loader)
{
    glGenProgramsARB(1, &mProgramID);
}

GLArbGpuProgram::~GLArbGpuProgram()
{
    // have to call this here reather than in Resource destructor
    // since calling virtual methods in base destructors causes crash
    unload();
}

void GLArbGpuProgram::bindProgram(void)
{
    glEnable(getProgramType());
    glBindProgramARB(getProgramType(), mProgramID);
}

void GLArbGpuProgram::unbindProgram(void)
{
    glBindProgramARB(getProgramType(), 0);
    glDisable(getProgramType());
}

void GLArbGpuProgram::bindProgramParameters(GpuProgramParametersSharedPtr params, uint16 mask)
{
    GLenum type = getProgramType();

    // only supports float constants
    GpuLogicalBufferStructPtr floatStruct = params->getFloatLogicalBufferStruct();

    for (GpuLogicalIndexUseMap::const_iterator i = floatStruct->map.begin();
        i != floatStruct->map.end(); ++i)
    {
        if (i->second.variability & mask)
        {
            GLuint logicalIndex = static_cast<GLuint>(i->first);
            const float* pFloat = params->getFloatPointer(i->second.physicalIndex);
            // Iterate over the params, set in 4-float chunks (low-level)
            for (size_t j = 0; j < i->second.currentSize; j+=4)
            {
                glProgramLocalParameter4fvARB(type, logicalIndex, pFloat);
                pFloat += 4;
                ++logicalIndex;
            }
        }
    }
}

void GLArbGpuProgram::bindProgramPassIterationParameters(GpuProgramParametersSharedPtr params)
{
    if (params->hasPassIterationNumber())
    {
        GLenum type = getProgramType();

        size_t physicalIndex = params->getPassIterationNumberIndex();
        size_t logicalIndex = params->getFloatLogicalIndexForPhysicalIndex(physicalIndex);
        const float* pFloat = params->getFloatPointer(physicalIndex);
        glProgramLocalParameter4fvARB(type, (GLuint)logicalIndex, pFloat);
    }

}

void GLArbGpuProgram::unloadImpl(void)
{
    glDeleteProgramsARB(1, &mProgramID);
}

void GLArbGpuProgram::loadFromSource(void)
{
    if (GL_INVALID_OPERATION == glGetError()) {
        LogManager::getSingleton().logMessage("Invalid Operation before loading program "+mName, LML_CRITICAL);

    }
    glBindProgramARB(getProgramType(), mProgramID);
    glProgramStringARB(getProgramType(), GL_PROGRAM_FORMAT_ASCII_ARB, (GLsizei)mSource.length(), mSource.c_str());

    if (GL_INVALID_OPERATION == glGetError())
    {
        GLint errPos;
        glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &errPos);
        const char* errStr = (const char*)glGetString(GL_PROGRAM_ERROR_STRING_ARB);
        OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "'" + mName + "' " + errStr);
    }
    glBindProgramARB(getProgramType(), 0);
}

}
<|endoftext|>


<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2014 Max-Planck-Institute for Intelligent Systems,
 *                     University of Southern California
 *    Jan Issac (jan.issac@gmail.com)
 *    Manuel Wuthrich (manuel.wuthrich@gmail.com)
 *
 *
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 */

/**
 * @date 2015
 * @author Manuel Wuthrich (manuel.wuthrich@gmail.com)
 * Max-Planck-Institute for Intelligent Systems
 */

#include <gtest/gtest.h>

#include <vector>

#include <fl/distribution/discrete_distribution.hpp>
#include <fl/distribution/gaussian.hpp>

#include <Eigen/Core>
#include <Eigen/Eigenvalues>

TEST(discrete_distribution, moments)
{
    typedef Eigen::Vector3d Variate;
    typedef Eigen::Matrix3d Covariance;
    typedef Variate::Scalar Scalar;
    typedef fl::DiscreteDistribution<Variate> DiscreteDistribution;
    typedef DiscreteDistribution::Function Function;

    // pick some mean and covariance
    Covariance covariance;
    covariance  <<  4.4, 2.1, -1.3,
                    2.2, 5.6,  1.2,
                   -1.2, 1.9,  3.9;
    covariance = covariance * covariance.transpose();

    Variate mean;
    mean << 2.1, 50.2, 20.1;

    // create gaussian
    fl::Gaussian<Variate> gaussian;
    gaussian.mean(mean);
    gaussian.covariance(covariance);

    // generate a sum of delta from gaussian
    DiscreteDistribution discrete_distribution;
    discrete_distribution.log_unnormalized_prob_mass(Function::Zero(100000));

    for(size_t i = 0; i < discrete_distribution.size(); i++)
    {
        discrete_distribution.location(i) = gaussian.sample();
    }

    // compare mean and covariance
    Covariance covariance_delta =
           discrete_distribution.covariance().inverse() * gaussian.covariance();

    EXPECT_TRUE(covariance_delta.isApprox(Covariance::Identity(), 0.1));

    EXPECT_TRUE((gaussian.square_root().inverse() *
                             (discrete_distribution.mean()-mean)).norm() < 0.1);
}

TEST(discrete_distribution, entropy)
{
    typedef Eigen::Vector3d Variate;
    typedef Variate::Scalar Scalar;
    typedef fl::DiscreteDistribution<Variate> DiscreteDistribution;
    typedef DiscreteDistribution::Function Function;

    int N = 100000;

    // check entropy of uniform distribution
    DiscreteDistribution discrete_distribution;
    discrete_distribution.log_unnormalized_prob_mass(Function::Zero(N));

    EXPECT_TRUE(fabs(std::log(double(discrete_distribution.size()))
                     - discrete_distribution.entropy()) < 0.0000001);

    EXPECT_TRUE(fabs(discrete_distribution.kl_given_uniform()) < 0.0000001);

    // check entropy of certain distribution
    Function log_pmf = Function::Constant(N,-std::numeric_limits<double>::max());
    log_pmf(0) = 0;
    discrete_distribution.log_unnormalized_prob_mass(log_pmf);

    EXPECT_TRUE(fabs(discrete_distribution.entropy()) < 0.0000001);

    EXPECT_TRUE(fabs(std::log(double(discrete_distribution.size()))
                     - discrete_distribution.kl_given_uniform()) < 0.0000001);
}

TEST(discrete_distribution, sampling)
{
    typedef Eigen::Matrix<int, 1, 1> Variate;
    typedef fl::DiscreteDistribution<Variate> DiscreteDistribution;
    typedef DiscreteDistribution::Function Function;
    typedef std::vector<Variate> Locations;

    int N_locations = 10;
    int N_samples   = 1000000;

    // random prob mass fct
    Function pmf = Function::Random(N_locations).abs() + 0.01;
    pmf /= pmf.sum();

    // create discrete distr
    DiscreteDistribution discrete_distribution;
    discrete_distribution.log_unnormalized_prob_mass(pmf.log());

    for(int i = 0; i < N_locations; i++)
        discrete_distribution.location(i)(0) = i;

    // generate empirical pmf
    Function empirical_pmf = Function::Zero(N_locations);
    for(int i = 0; i < N_samples; i++)
    {
        empirical_pmf(discrete_distribution.sample()(0)) += 1./N_samples;
    }

    // make sure that pmf and empirical pmf are similar
    for(int i = 0; i < pmf.size(); i++)
    {
        EXPECT_TRUE(fabs(pmf[i] - empirical_pmf[i]) < 0.01);
    }
}

<commit_msg>License updated<commit_after>/*
 * This is part of the FL library, a C++ Bayesian filtering library
 * (https://github.com/filtering-library)
 *
 * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)
 * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)
 *
 * Max-Planck Institute for Intelligent Systems, AMD Lab
 * University of Southern California, CLMC Lab
 *
 * This Source Code Form is subject to the terms of the MIT License (MIT).
 * A copy of the license can be found in the LICENSE file distributed with this
 * source code.
 */
/**
 * @date 2015
 * @author Manuel Wuthrich (manuel.wuthrich@gmail.com)
 * Max-Planck-Institute for Intelligent Systems
 */

#include <gtest/gtest.h>

#include <vector>

#include <fl/distribution/discrete_distribution.hpp>
#include <fl/distribution/gaussian.hpp>

#include <Eigen/Core>
#include <Eigen/Eigenvalues>

TEST(discrete_distribution, moments)
{
    typedef Eigen::Vector3d Variate;
    typedef Eigen::Matrix3d Covariance;
    typedef Variate::Scalar Scalar;
    typedef fl::DiscreteDistribution<Variate> DiscreteDistribution;
    typedef DiscreteDistribution::Function Function;

    // pick some mean and covariance
    Covariance covariance;
    covariance  <<  4.4, 2.1, -1.3,
                    2.2, 5.6,  1.2,
                   -1.2, 1.9,  3.9;
    covariance = covariance * covariance.transpose();

    Variate mean;
    mean << 2.1, 50.2, 20.1;

    // create gaussian
    fl::Gaussian<Variate> gaussian;
    gaussian.mean(mean);
    gaussian.covariance(covariance);

    // generate a sum of delta from gaussian
    DiscreteDistribution discrete_distribution;
    discrete_distribution.log_unnormalized_prob_mass(Function::Zero(100000));

    for(size_t i = 0; i < discrete_distribution.size(); i++)
    {
        discrete_distribution.location(i) = gaussian.sample();
    }

    // compare mean and covariance
    Covariance covariance_delta =
           discrete_distribution.covariance().inverse() * gaussian.covariance();

    EXPECT_TRUE(covariance_delta.isApprox(Covariance::Identity(), 0.1));

    EXPECT_TRUE((gaussian.square_root().inverse() *
                             (discrete_distribution.mean()-mean)).norm() < 0.1);
}

TEST(discrete_distribution, entropy)
{
    typedef Eigen::Vector3d Variate;
    typedef Variate::Scalar Scalar;
    typedef fl::DiscreteDistribution<Variate> DiscreteDistribution;
    typedef DiscreteDistribution::Function Function;

    int N = 100000;

    // check entropy of uniform distribution
    DiscreteDistribution discrete_distribution;
    discrete_distribution.log_unnormalized_prob_mass(Function::Zero(N));

    EXPECT_TRUE(fabs(std::log(double(discrete_distribution.size()))
                     - discrete_distribution.entropy()) < 0.0000001);

    EXPECT_TRUE(fabs(discrete_distribution.kl_given_uniform()) < 0.0000001);

    // check entropy of certain distribution
    Function log_pmf = Function::Constant(N,-std::numeric_limits<double>::max());
    log_pmf(0) = 0;
    discrete_distribution.log_unnormalized_prob_mass(log_pmf);

    EXPECT_TRUE(fabs(discrete_distribution.entropy()) < 0.0000001);

    EXPECT_TRUE(fabs(std::log(double(discrete_distribution.size()))
                     - discrete_distribution.kl_given_uniform()) < 0.0000001);
}

TEST(discrete_distribution, sampling)
{
    typedef Eigen::Matrix<int, 1, 1> Variate;
    typedef fl::DiscreteDistribution<Variate> DiscreteDistribution;
    typedef DiscreteDistribution::Function Function;
    typedef std::vector<Variate> Locations;

    int N_locations = 10;
    int N_samples   = 1000000;

    // random prob mass fct
    Function pmf = Function::Random(N_locations).abs() + 0.01;
    pmf /= pmf.sum();

    // create discrete distr
    DiscreteDistribution discrete_distribution;
    discrete_distribution.log_unnormalized_prob_mass(pmf.log());

    for(int i = 0; i < N_locations; i++)
        discrete_distribution.location(i)(0) = i;

    // generate empirical pmf
    Function empirical_pmf = Function::Zero(N_locations);
    for(int i = 0; i < N_samples; i++)
    {
        empirical_pmf(discrete_distribution.sample()(0)) += 1./N_samples;
    }

    // make sure that pmf and empirical pmf are similar
    for(int i = 0; i < pmf.size(); i++)
    {
        EXPECT_TRUE(fabs(pmf[i] - empirical_pmf[i]) < 0.01);
    }
}
<|endoftext|>