<commit_before>#include "threadHelper.h"

#ifdef __unix__
#include <pthread.h>
#else
#include <windows.h>
#endif
#include "Logger.h"

using namespace lime;

#ifdef __unix__
int lime::SetOSThreadPriority(ThreadPriority priority, ThreadPolicy policy, std::thread *thread)
{
    if (!thread)
    {
        lime::debug("SetOSThreadPriority: null thread pointer");
        return -1;
    }

    int sched_policy = SCHED_OTHER;

    switch (policy)
    {
    case ThreadPolicy::DEFAULT:
        sched_policy = SCHED_OTHER;
        break;
    case ThreadPolicy::REALTIME:
        sched_policy = SCHED_RR;
        break;
    case ThreadPolicy::PREEMPTIVE:
        sched_policy = SCHED_FIFO;
        break;
    }

    int prio_min = sched_get_priority_min(sched_policy);
    int prio_max = sched_get_priority_max(sched_policy);

    if (prio_min == -1 || prio_max == -1)
    {
        lime::debug("SetOSThreadPriority: Failed to get available priority values");
        return -1;
    }

    //scale values
    sched_param sch;
    sch.sched_priority = int(((prio_max - prio_min) / (float)ThreadPriority::HIGHEST) * priority) + prio_min;

    if (int ret = pthread_setschedparam(thread->native_handle(), sched_policy, &sch))
    {
        lime::debug("SetOSThreadPriority: Failed to set priority(%d), schec_prio(%d), policy(%d), ret(%d)",
                    priority, sched_policy, ret, sch.sched_priority);
        return -1;
    }

    return 0;
}

int lime::SetOSCurrentThreadPriority(ThreadPriority priority, ThreadPolicy policy)
{
    int sched_policy = SCHED_OTHER;

    switch (policy)
    {
    case ThreadPolicy::DEFAULT:
        sched_policy = SCHED_OTHER;
        break;
    case ThreadPolicy::REALTIME:
        sched_policy = SCHED_RR;
        break;
    case ThreadPolicy::PREEMPTIVE:
        sched_policy = SCHED_FIFO;
        break;
    }

    int prio_min = sched_get_priority_min(sched_policy);
    int prio_max = sched_get_priority_max(sched_policy);

    if (prio_min == -1 || prio_max == -1)
    {
        lime::debug("SetOSCurrentThreadPriority: Failed to get available priority values");
        return -1;
    }

    //scale values
    sched_param sch;
    sch.sched_priority = int(((prio_max - prio_min) / (float)ThreadPriority::HIGHEST) * priority) + prio_min;

    if (int ret = pthread_setschedparam(pthread_self(), sched_policy, &sch) != 0)
    {
        lime::debug("SetOSCurrentThreadPriority: Failed to set priority(%d), schec_prio(%d), policy(%d), ret(%d)",
                    priority, sched_policy, ret, sch.sched_priority);
        return -1;
    }

    return 0;
}

#elif _WIN32

int lime::SetOSThreadPriority(ThreadPriority priority, ThreadPolicy /*policy*/, std::thread *thread)
{
    if (!thread)
    {
        lime::debug("SetOSThreadPriority: null thread pointer");
        return -1;
    }

    int win_priority = THREAD_PRIORITY_NORMAL;

    switch (priority)
    {
    case ThreadPriority::LOWEST:
        win_priority = THREAD_PRIORITY_IDLE;
        break;
    case ThreadPriority::LOW:
        win_priority = THREAD_PRIORITY_LOWEST;
        break;
    case ThreadPriority::BELOW_NORMAL:
        win_priority = THREAD_PRIORITY_BELOW_NORMAL;
        break;
    case ThreadPriority::NORMAL:
        win_priority = THREAD_PRIORITY_NORMAL;
        break;
    case ThreadPriority::ABOVE_NORMAL:
        win_priority = THREAD_PRIORITY_ABOVE_NORMAL;
        break;
    case ThreadPriority::HIGH:
        win_priority = THREAD_PRIORITY_HIGHEST;
        break;
    case ThreadPriority::HIGHEST:
        win_priority = THREAD_PRIORITY_TIME_CRITICAL;
        break;
    }

    if (!SetThreadPriority(thread->native_handle(), win_priority))
    {
        lime::debug("SetThreadPriority: Failed to set priority(%d)", win_priority);
        return -1;
    }
    return 0;
}

int lime::SetOSCurrentThreadPriority(ThreadPriority priority, ThreadPolicy /*policy*/)
{
    int win_priority = THREAD_PRIORITY_NORMAL;

    switch (priority)
    {
    case ThreadPriority::LOWEST:
        win_priority = THREAD_PRIORITY_IDLE;
        break;
    case ThreadPriority::LOW:
        win_priority = THREAD_PRIORITY_LOWEST;
        break;
    case ThreadPriority::BELOW_NORMAL:
        win_priority = THREAD_PRIORITY_BELOW_NORMAL;
        break;
    case ThreadPriority::NORMAL:
        win_priority = THREAD_PRIORITY_NORMAL;
        break;
    case ThreadPriority::ABOVE_NORMAL:
        win_priority = THREAD_PRIORITY_ABOVE_NORMAL;
        break;
    case ThreadPriority::HIGH:
        win_priority = THREAD_PRIORITY_HIGHEST;
        break;
    case ThreadPriority::HIGHEST:
        win_priority = THREAD_PRIORITY_TIME_CRITICAL;
        break;
    }

    if (!SetThreadPriority(GetCurrentThread(), win_priority))
    {
        lime::debug("SetThreadPriority: Failed to set priority(%d)", win_priority);
        return -1;
    }
}
#else

int lime::SetOSThreadPriority(ThreadPriority priority, ThreadPolicy policy, std::thread *thread)
{
    return 0;
}

int lime::SetOSCurrentThreadPriority(ThreadPriority priority, ThreadPolicy policy)
{
    return 0;
}
#endif
<commit_msg>Fix threadHelper return value<commit_after>#include "threadHelper.h"

#ifdef __unix__
#include <pthread.h>
#else
#include <windows.h>
#endif
#include "Logger.h"

using namespace lime;

#ifdef __unix__
int lime::SetOSThreadPriority(ThreadPriority priority, ThreadPolicy policy, std::thread *thread)
{
    if (!thread)
    {
        lime::debug("SetOSThreadPriority: null thread pointer");
        return -1;
    }

    int sched_policy = SCHED_OTHER;

    switch (policy)
    {
    case ThreadPolicy::DEFAULT:
        sched_policy = SCHED_OTHER;
        break;
    case ThreadPolicy::REALTIME:
        sched_policy = SCHED_RR;
        break;
    case ThreadPolicy::PREEMPTIVE:
        sched_policy = SCHED_FIFO;
        break;
    }

    int prio_min = sched_get_priority_min(sched_policy);
    int prio_max = sched_get_priority_max(sched_policy);

    if (prio_min == -1 || prio_max == -1)
    {
        lime::debug("SetOSThreadPriority: Failed to get available priority values");
        return -1;
    }

    //scale values
    sched_param sch;
    sch.sched_priority = int(((prio_max - prio_min) / (float)ThreadPriority::HIGHEST) * priority) + prio_min;

    if (int ret = pthread_setschedparam(thread->native_handle(), sched_policy, &sch))
    {
        lime::debug("SetOSThreadPriority: Failed to set priority(%d), schec_prio(%d), policy(%d), ret(%d)",
                    priority, sched_policy, ret, sch.sched_priority);
        return -1;
    }

    return 0;
}

int lime::SetOSCurrentThreadPriority(ThreadPriority priority, ThreadPolicy policy)
{
    int sched_policy = SCHED_OTHER;

    switch (policy)
    {
    case ThreadPolicy::DEFAULT:
        sched_policy = SCHED_OTHER;
        break;
    case ThreadPolicy::REALTIME:
        sched_policy = SCHED_RR;
        break;
    case ThreadPolicy::PREEMPTIVE:
        sched_policy = SCHED_FIFO;
        break;
    }

    int prio_min = sched_get_priority_min(sched_policy);
    int prio_max = sched_get_priority_max(sched_policy);

    if (prio_min == -1 || prio_max == -1)
    {
        lime::debug("SetOSCurrentThreadPriority: Failed to get available priority values");
        return -1;
    }

    //scale values
    sched_param sch;
    sch.sched_priority = int(((prio_max - prio_min) / (float)ThreadPriority::HIGHEST) * priority) + prio_min;

    if (int ret = pthread_setschedparam(pthread_self(), sched_policy, &sch) != 0)
    {
        lime::debug("SetOSCurrentThreadPriority: Failed to set priority(%d), schec_prio(%d), policy(%d), ret(%d)",
                    priority, sched_policy, ret, sch.sched_priority);
        return -1;
    }

    return 0;
}

#elif _WIN32

int lime::SetOSThreadPriority(ThreadPriority priority, ThreadPolicy /*policy*/, std::thread *thread)
{
    if (!thread)
    {
        lime::debug("SetOSThreadPriority: null thread pointer");
        return -1;
    }

    int win_priority = THREAD_PRIORITY_NORMAL;

    switch (priority)
    {
    case ThreadPriority::LOWEST:
        win_priority = THREAD_PRIORITY_IDLE;
        break;
    case ThreadPriority::LOW:
        win_priority = THREAD_PRIORITY_LOWEST;
        break;
    case ThreadPriority::BELOW_NORMAL:
        win_priority = THREAD_PRIORITY_BELOW_NORMAL;
        break;
    case ThreadPriority::NORMAL:
        win_priority = THREAD_PRIORITY_NORMAL;
        break;
    case ThreadPriority::ABOVE_NORMAL:
        win_priority = THREAD_PRIORITY_ABOVE_NORMAL;
        break;
    case ThreadPriority::HIGH:
        win_priority = THREAD_PRIORITY_HIGHEST;
        break;
    case ThreadPriority::HIGHEST:
        win_priority = THREAD_PRIORITY_TIME_CRITICAL;
        break;
    }

    if (!SetThreadPriority(thread->native_handle(), win_priority))
    {
        lime::debug("SetThreadPriority: Failed to set priority(%d)", win_priority);
        return -1;
    }
    return 0;
}

int lime::SetOSCurrentThreadPriority(ThreadPriority priority, ThreadPolicy /*policy*/)
{
    int win_priority = THREAD_PRIORITY_NORMAL;

    switch (priority)
    {
    case ThreadPriority::LOWEST:
        win_priority = THREAD_PRIORITY_IDLE;
        break;
    case ThreadPriority::LOW:
        win_priority = THREAD_PRIORITY_LOWEST;
        break;
    case ThreadPriority::BELOW_NORMAL:
        win_priority = THREAD_PRIORITY_BELOW_NORMAL;
        break;
    case ThreadPriority::NORMAL:
        win_priority = THREAD_PRIORITY_NORMAL;
        break;
    case ThreadPriority::ABOVE_NORMAL:
        win_priority = THREAD_PRIORITY_ABOVE_NORMAL;
        break;
    case ThreadPriority::HIGH:
        win_priority = THREAD_PRIORITY_HIGHEST;
        break;
    case ThreadPriority::HIGHEST:
        win_priority = THREAD_PRIORITY_TIME_CRITICAL;
        break;
    }

    if (!SetThreadPriority(GetCurrentThread(), win_priority))
    {
        lime::debug("SetThreadPriority: Failed to set priority(%d)", win_priority);
        return -1;
    }
    return 0;
}
#else

int lime::SetOSThreadPriority(ThreadPriority priority, ThreadPolicy policy, std::thread *thread)
{
    return 0;
}

int lime::SetOSCurrentThreadPriority(ThreadPriority priority, ThreadPolicy policy)
{
    return 0;
}
#endif
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_npu_scominit.H $   */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file p9_npu_scominit.C
/// @brief Apply SCOM overrides for the NPU unit via an init file
///
// *HWP HWP Owner: Joe McGill <jmcgill@us.ibm.com>
// *HWP FW Owner: Thi Tran <thi@us.ibm.com>
// *HWP Team: Nest
// *HWP Level: 2
// *HWP Consumed by: HB

#ifndef _PROC_NPU_SCOMINIT_H_
#define _PROC_NPU_SCOMINIT_H_

//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <fapi2.H>

//------------------------------------------------------------------------------
// Structure definitions
//------------------------------------------------------------------------------
// function pointer typedef definition for HWP call support
typedef fapi2::ReturnCode (*p9_npu_scominit_FP_t)(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);

//------------------------------------------------------------------------------
// Function prototypes
//------------------------------------------------------------------------------
extern "C"
{

///
/// @brief Apply SCOM overrides for the NPU unit via an init file
/// @param[in] i_target Reference to processor chip target
/// @return fapi2::ReturnCode. FAPI2_RC_SUCCESS if success, else error code.
///
    fapi2::ReturnCode p9_npu_scominit(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target);

} // extern "C"

#endif // _PROC_NPU_SCOMINIT_H_
<commit_msg>L3 update -- p9_npu_scominit<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_npu_scominit.H $   */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file p9_npu_scominit.C
/// @brief Apply SCOM overrides for the NPU, enable NVLINK refclocks
///
// *HWP HWP Owner: Joe McGill <jmcgill@us.ibm.com>
// *HWP FW Owner: Thi Tran <thi@us.ibm.com>
// *HWP Team: Nest
// *HWP Level: 3
// *HWP Consumed by: HB

#ifndef _PROC_NPU_SCOMINIT_H_
#define _PROC_NPU_SCOMINIT_H_

//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <fapi2.H>

//------------------------------------------------------------------------------
// Structure definitions
//------------------------------------------------------------------------------
// function pointer typedef definition for HWP call support
typedef fapi2::ReturnCode (*p9_npu_scominit_FP_t) (
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);

//------------------------------------------------------------------------------
// Function prototypes
//------------------------------------------------------------------------------
extern "C"
{

///
/// @brief Apply SCOM overrides for the NPU unit via an init file
/// @param[in] i_target Reference to processor chip target
/// @return fapi2::ReturnCode. FAPI2_RC_SUCCESS if success, else error code.
///
    fapi2::ReturnCode p9_npu_scominit(
        const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target);

} // extern "C"

#endif // _PROC_NPU_SCOMINIT_H_
<|endoftext|>


<commit_before>#include <stingraykit/signal/signals.h>
#include <stingraykit/signal/ValueFromSignalObtainer.h>

#include <gtest/gtest.h>

#include <list>

using namespace stingray;

void PopulateBool(const function<void (bool)>& slot)
{ slot(true); }

void PopulateIntPtr(const function<void (shared_ptr<int>)>& slot)
{ slot(make_shared_ptr<int>(42)); }

void PopulateVoid(const function<void ()>& slot)
{ slot(); }

void PopulateBoolCollection(const function<void (CollectionOp, bool)>& slot)
{
	slot(CollectionOp::Added, false);
	slot(CollectionOp::Added, true);
}

void PopulateMultiple(const function<void (int, const std::string&, bool)>& slot)
{ slot(42, "test", true); }

TEST(ValueFromSignal, Obtainer)
{
	stingray::signal<void (bool)> s1;
	stingray::signal<void (bool)> s2(&PopulateBool);

	ValueFromSignalObtainer<bool> obtainer;

	s1.SendCurrentState(obtainer);
	ASSERT_EQ(obtainer.HasValue(), false);
	ASSERT_ANY_THROW(obtainer.GetValue());

	s2.SendCurrentState(obtainer);
	ASSERT_EQ(obtainer.HasValue(), true);
	ASSERT_EQ(obtainer.GetValue(), true);

	ASSERT_ANY_THROW(PopulateBool(obtainer));
}

TEST(ValueFromSignal, ObtainerVoid)
{
	stingray::signal<void ()> s1;
	stingray::signal<void ()> s2(&PopulateVoid);

	ValueFromSignalObtainer<void> obtainer;

	s1.SendCurrentState(obtainer);
	ASSERT_EQ(obtainer.HasValue(), false);

	s2.SendCurrentState(obtainer);
	ASSERT_EQ(obtainer.HasValue(), true);

	ASSERT_ANY_THROW(PopulateVoid(obtainer));
}

TEST(ValueFromSignal, Collector)
{
	stingray::signal<void (CollectionOp, bool)> s1;
	stingray::signal<void (CollectionOp, bool)> s2(&PopulateBoolCollection);

	ValuesFromSignalCollector<std::list<bool> > collector;

	s1.SendCurrentState(collector);
	ASSERT_EQ(collector.GetValues().size(), 0u);

	s2.SendCurrentState(collector);
	ASSERT_EQ(collector.GetValues().size(), 2u);
}

TEST(ValueFromSignal, Tuple)
{
	stingray::signal<void (int, const std::string&, bool)> s1;
	stingray::signal<void (int, const std::string&, bool)> s2(&PopulateMultiple);

	TupleFromSignalObtainer<int, std::string, bool> obtainer;

	s1.SendCurrentState(obtainer);
	ASSERT_FALSE(obtainer.HasValues());
	ASSERT_ANY_THROW(obtainer.GetValues());

	s2.SendCurrentState(obtainer);
	ASSERT_TRUE(obtainer.HasValues());
	ASSERT_EQ(obtainer.GetValue<0>(), 42);
	ASSERT_EQ(obtainer.GetValue<1>(), "test");
	ASSERT_EQ(obtainer.GetValue<2>(), true);

	ASSERT_ANY_THROW(PopulateMultiple(obtainer));
}

TEST(ValueFromSignal, Getter)
{
	stingray::signal<void (bool)> s1;
	stingray::signal<void (bool)> s2(&PopulateBool);
	stingray::signal<void (shared_ptr<int>)> s3;
	stingray::signal<void (shared_ptr<int>)> s4(&PopulateIntPtr);

	ASSERT_EQ(HasValueInSignal(s1.connector()), false);
	ASSERT_EQ(GetValueFromSignal(s1.connector()), null);

	ASSERT_EQ(HasValueInSignal(s2.connector()), true);
	ASSERT_EQ(GetValueFromSignal(s2.connector()), true);

	ASSERT_EQ(HasValueInSignal(s3.connector()), false);
	ASSERT_FALSE(GetValueFromSignal(s3.connector()));

	ASSERT_EQ(HasValueInSignal(s4.connector()), true);
	ASSERT_TRUE(GetValueFromSignal(s4.connector()));
	ASSERT_EQ(*GetValueFromSignal(s4.connector()), 42);
}

TEST(ValueFromSignal, GetterVoid)
{
	stingray::signal<void ()> s1;
	stingray::signal<void ()> s2(&PopulateVoid);

	ASSERT_EQ(HasValueInSignal(s1.connector()), false);
	ASSERT_EQ(HasValueInSignal(s2.connector()), true);
}

TEST(ValueFromSignal, CollectorGetter)
{
	stingray::signal<void (CollectionOp, bool)> s1;
	stingray::signal<void (CollectionOp, bool)> s2(&PopulateBoolCollection);

	ASSERT_EQ(GetValuesFromSignal<std::list<bool> >(s1.connector()).size(), 0u);
	ASSERT_EQ(GetValuesFromSignal<std::list<bool> >(s2.connector()).size(), 2u);
}

TEST(ValueFromSignal, TupleGetter)
{
	stingray::signal<void (int, const std::string&, bool)> s1;
	stingray::signal<void (int, const std::string&, bool)> s2(&PopulateMultiple);

	ASSERT_FALSE(HasTupleInSignal(s1.connector()));
	ASSERT_EQ(GetTupleFromSignal(s1.connector()), null);

	ASSERT_TRUE(HasTupleInSignal(s2.connector()));
	ASSERT_TRUE(TupleEquals()(*GetTupleFromSignal(s2.connector()), MakeTuple(42, std::string("test"), true)));
}
<commit_msg>unittests/ValueFromSignal: add more tests for values collector<commit_after>#include <stingraykit/signal/signals.h>
#include <stingraykit/signal/ValueFromSignalObtainer.h>

#include <gtest/gtest.h>

#include <list>

using namespace stingray;

void PopulateBool(const function<void (bool)>& slot)
{ slot(true); }

void PopulateIntPtr(const function<void (shared_ptr<int>)>& slot)
{ slot(make_shared_ptr<int>(42)); }

void PopulateVoid(const function<void ()>& slot)
{ slot(); }

void PopulateBoolCollection(const function<void (CollectionOp, bool)>& slot)
{
	slot(CollectionOp::Added, false);
	slot(CollectionOp::Added, true);
}

void PopulateMultiple(const function<void (int, const std::string&, bool)>& slot)
{ slot(42, "test", true); }

TEST(ValueFromSignal, Obtainer)
{
	stingray::signal<void (bool)> s1;
	stingray::signal<void (bool)> s2(&PopulateBool);

	ValueFromSignalObtainer<bool> obtainer;

	s1.SendCurrentState(obtainer);
	ASSERT_EQ(obtainer.HasValue(), false);
	ASSERT_ANY_THROW(obtainer.GetValue());

	s2.SendCurrentState(obtainer);
	ASSERT_EQ(obtainer.HasValue(), true);
	ASSERT_EQ(obtainer.GetValue(), true);

	ASSERT_ANY_THROW(PopulateBool(obtainer));
}

TEST(ValueFromSignal, ObtainerVoid)
{
	stingray::signal<void ()> s1;
	stingray::signal<void ()> s2(&PopulateVoid);

	ValueFromSignalObtainer<void> obtainer;

	s1.SendCurrentState(obtainer);
	ASSERT_EQ(obtainer.HasValue(), false);

	s2.SendCurrentState(obtainer);
	ASSERT_EQ(obtainer.HasValue(), true);

	ASSERT_ANY_THROW(PopulateVoid(obtainer));
}

TEST(ValueFromSignal, Collector)
{
	stingray::signal<void (CollectionOp, bool)> s1;
	stingray::signal<void (CollectionOp, bool)> s2(&PopulateBoolCollection);
	stingray::signal<void (bool)> s3(&PopulateBool);

	ValuesFromSignalCollector<std::list<bool> > collector;

	s1.SendCurrentState(collector);
	ASSERT_EQ(collector.GetValues().size(), 0u);

	s2.SendCurrentState(collector);
	ASSERT_EQ(collector.GetValues().size(), 2u);

	s3.SendCurrentState(collector);
	ASSERT_EQ(collector.GetValues().size(), 3u);
}

TEST(ValueFromSignal, Tuple)
{
	stingray::signal<void (int, const std::string&, bool)> s1;
	stingray::signal<void (int, const std::string&, bool)> s2(&PopulateMultiple);

	TupleFromSignalObtainer<int, std::string, bool> obtainer;

	s1.SendCurrentState(obtainer);
	ASSERT_FALSE(obtainer.HasValues());
	ASSERT_ANY_THROW(obtainer.GetValues());

	s2.SendCurrentState(obtainer);
	ASSERT_TRUE(obtainer.HasValues());
	ASSERT_EQ(obtainer.GetValue<0>(), 42);
	ASSERT_EQ(obtainer.GetValue<1>(), "test");
	ASSERT_EQ(obtainer.GetValue<2>(), true);

	ASSERT_ANY_THROW(PopulateMultiple(obtainer));
}

TEST(ValueFromSignal, Getter)
{
	stingray::signal<void (bool)> s1;
	stingray::signal<void (bool)> s2(&PopulateBool);
	stingray::signal<void (shared_ptr<int>)> s3;
	stingray::signal<void (shared_ptr<int>)> s4(&PopulateIntPtr);

	ASSERT_EQ(HasValueInSignal(s1.connector()), false);
	ASSERT_EQ(GetValueFromSignal(s1.connector()), null);

	ASSERT_EQ(HasValueInSignal(s2.connector()), true);
	ASSERT_EQ(GetValueFromSignal(s2.connector()), true);

	ASSERT_EQ(HasValueInSignal(s3.connector()), false);
	ASSERT_FALSE(GetValueFromSignal(s3.connector()));

	ASSERT_EQ(HasValueInSignal(s4.connector()), true);
	ASSERT_TRUE(GetValueFromSignal(s4.connector()));
	ASSERT_EQ(*GetValueFromSignal(s4.connector()), 42);
}

TEST(ValueFromSignal, GetterVoid)
{
	stingray::signal<void ()> s1;
	stingray::signal<void ()> s2(&PopulateVoid);

	ASSERT_EQ(HasValueInSignal(s1.connector()), false);
	ASSERT_EQ(HasValueInSignal(s2.connector()), true);
}

TEST(ValueFromSignal, CollectorGetter)
{
	stingray::signal<void (CollectionOp, bool)> s1;
	stingray::signal<void (CollectionOp, bool)> s2(&PopulateBoolCollection);

	ASSERT_EQ(GetValuesFromSignal<std::list<bool> >(s1.connector()).size(), 0u);
	ASSERT_EQ(GetValuesFromSignal<std::list<bool> >(s2.connector()).size(), 2u);
}

TEST(ValueFromSignal, TupleGetter)
{
	stingray::signal<void (int, const std::string&, bool)> s1;
	stingray::signal<void (int, const std::string&, bool)> s2(&PopulateMultiple);

	ASSERT_FALSE(HasTupleInSignal(s1.connector()));
	ASSERT_EQ(GetTupleFromSignal(s1.connector()), null);

	ASSERT_TRUE(HasTupleInSignal(s2.connector()));
	ASSERT_TRUE(TupleEquals()(*GetTupleFromSignal(s2.connector()), MakeTuple(42, std::string("test"), true)));
}
<|endoftext|>


<commit_before>/******************************************************************************

  This source file is part of the tomviz project.

  Copyright Kitware, Inc.

  This source code is released under the New BSD License, (the "License").

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

******************************************************************************/
#include "RecentFilesMenu.h"

#include "ActiveObjects.h"
#include "DataSource.h"
#include "LoadDataReaction.h"
#include "pqPipelineSource.h"
#include "pqSettings.h"
#include "SaveLoadStateReaction.h"
#include "Utilities.h"
#include "vtkNew.h"
#include "vtkSmartPointer.h"
#include "vtkSMCoreUtilities.h"
#include "vtkSMParaViewPipelineController.h"
#include "vtkSMPropertyHelper.h"
#include "vtkSMSessionProxyManager.h"
#include "vtkSMSourceProxy.h"

#include <QMenu>
#include <QDebug>
#include <sstream>
#include <string>

namespace tomviz
{

static const int MAX_ITEMS = 10;

void get_settings(pugi::xml_document& doc)
{
  QSettings* settings = pqApplicationCore::instance()->settings();
  QString recent = settings->value("recentFiles").toString();
  if (recent.isEmpty() || !doc.load(recent.toUtf8().data()) || !doc.child("tomvizRecentFilesMenu"))
  {
    doc.append_child("tomvizRecentFilesMenu");
  }
}

void save_settings(pugi::xml_document &doc)
{
  // trim the list.
  pugi::xml_node root = doc.root();
  std::vector<pugi::xml_node> to_remove;
  int counter=0;
  for (pugi::xml_node node = root.child("DataReader"); node;
       node = node.next_sibling("DataReader"), counter++)
  {
    if (counter >= MAX_ITEMS)
    {
      to_remove.push_back(node);
    }
  }
  counter=0;
  for (pugi::xml_node node = root.child("State"); node;
       node = node.next_sibling("State"), counter++)
  {
    if (counter >= MAX_ITEMS)
    {
      to_remove.push_back(node);
    }
  }
  for (size_t cc = 0; cc < to_remove.size(); cc++)
  {
    root.remove_child(to_remove[cc]);
  }

  std::ostringstream stream;
  doc.save(stream);
  QSettings* settings = pqApplicationCore::instance()->settings();
  settings->setValue("recentFiles", stream.str().c_str());
}

//-------------------------------------------------------------------------
RecentFilesMenu::RecentFilesMenu(QMenu& menu, QObject* parentObject)
  : Superclass(parentObject)
{
  this->connect(&menu, SIGNAL(aboutToShow()), SLOT(aboutToShowMenu()));
}

//-------------------------------------------------------------------------
RecentFilesMenu::~RecentFilesMenu()
{
}

//-------------------------------------------------------------------------
void RecentFilesMenu::pushDataReader(vtkSMProxy* readerProxy)
{
  pugi::xml_document settings;
  get_settings(settings);

  pugi::xml_node root = settings.root();
  const char* pname = vtkSMCoreUtilities::GetFileNameProperty(readerProxy);
  if (pname)
  {
    const char* filename = vtkSMPropertyHelper(readerProxy,
                                               pname).GetAsString(0);
    for (pugi::xml_node node = root.child("DataReader"); node;
         node = node.next_sibling("DataReader"))
    {
      if (strcmp(node.attribute("filename0").as_string(""), filename) == 0)
      {
        root.remove_child(node);
        break;
      }
    }
    pugi::xml_node node = root.prepend_child("DataReader");
    node.append_attribute("filename0").set_value(filename);
    node.append_attribute("xmlgroup").set_value(readerProxy->GetXMLGroup());
    node.append_attribute("xmlname").set_value(readerProxy->GetXMLName());
    tomviz::serialize(readerProxy, node);

    save_settings(settings);
  }
}

//-------------------------------------------------------------------------
void RecentFilesMenu::pushStateFile(const QString& filename)
{
  pugi::xml_document settings;
  get_settings(settings);

  pugi::xml_node root = settings.root();
  for (pugi::xml_node node = root.child("State"); node;
       node = node.next_sibling("State"))
  {
    if (filename == node.attribute("filename").as_string(""))
    {
      root.remove_child(node);
      break;
    }
  }

  pugi::xml_node node = root.prepend_child("State");
  node.append_attribute("filename").set_value(filename.toLatin1().data());
  save_settings(settings);
}

//-------------------------------------------------------------------------
void RecentFilesMenu::aboutToShowMenu()
{
  QMenu* menu = qobject_cast<QMenu*>(this->sender());
  Q_ASSERT(menu);
  menu->clear();

  pugi::xml_document settings;
  get_settings(settings);

  pugi::xml_node root = settings.root();
  if (!root.child("DataReader") && !root.child("State"))
  {
    QAction* actn = menu->addAction("Empty");
    actn->setEnabled(false);
    return;
  }

  bool header_added = false;
  int index=0;
  for (pugi::xml_node node = root.child("DataReader"); node;
       node = node.next_sibling("DataReader"))
  {
    if (header_added == false)
    {
      QAction* actn = menu->addAction("Datasets");
      actn->setEnabled(false);
      header_added = true;
    }
    QFileInfo checkFile(node.attribute("filename0").as_string("<bug>"));
    if (checkFile.exists())
    {
      QAction* actn = menu->addAction(QIcon(":/pqWidgets/Icons/pqInspect22.png"),
        node.attribute("filename0").as_string("<bug>"));
      actn->setData(index);
      this->connect(actn, SIGNAL(triggered()), SLOT(dataSourceTriggered()));
    }
    index++;
  }

  header_added = false;
  for (pugi::xml_node node = root.child("State"); node;
       node = node.next_sibling("State"))
  {
    if (header_added == false)
    {
      QAction* actn = menu->addAction("State files");
      actn->setEnabled(false);
      header_added = true;
    }
    QFileInfo checkFile(node.attribute("filename").as_string("<bug>"));
    if (checkFile.exists())
    {
      QAction* actn = menu->addAction(QIcon(":/icons/tomviz.png"),
        node.attribute("filename").as_string("<bug>"));
      actn->setData(node.attribute("filename").as_string("<bug>"));
      this->connect(actn, SIGNAL(triggered()), SLOT(stateTriggered()));
    }
    index++;
  }
}

//-------------------------------------------------------------------------
void RecentFilesMenu::dataSourceTriggered()
{
  QAction* actn = qobject_cast<QAction*>(this->sender());
  Q_ASSERT(actn);

  QFileInfo checkFile(actn->iconText());
  if (!checkFile.exists())
  {
    // This should never happen since the checks in aboutToShowMenu should
    // prevent it, but just in case...
    qWarning() << "Error: file '" << actn->iconText()
               << "' does not exist.";
    return;
  }

  int index = actn->data().toInt();
  pugi::xml_document settings;
  get_settings(settings);
  pugi::xml_node root = settings.root();

  for (pugi::xml_node node = root.child("DataReader"); node;
       node = node.next_sibling("DataReader"), --index)
  {
    if (index == 0)
    {
      vtkSMSessionProxyManager* pxm = ActiveObjects::instance().proxyManager();
      vtkSmartPointer<vtkSMProxy> reader;
      reader.TakeReference(pxm->NewProxy(node.attribute("xmlgroup").as_string(),
                                         node.attribute("xmlname").as_string()));
      if (tomviz::deserialize(reader, node))
      {
        reader->UpdateVTKObjects();
        vtkSMSourceProxy::SafeDownCast(reader)->UpdatePipelineInformation();
        if (LoadDataReaction::createDataSource(reader))
        {
          // reorder the nodes to move the recently opened file to the top.
          root.prepend_copy(node);
          root.remove_child(node);
          save_settings(settings);
          return;
        }
      }
      // failed to create reader, remove the node.
      root.remove_child(node);
      save_settings(settings);
      return;
    }
  }
}

//-------------------------------------------------------------------------
void RecentFilesMenu::stateTriggered()
{
  QAction* actn = qobject_cast<QAction*>(this->sender());
  Q_ASSERT(actn);

  QFileInfo checkFile(actn->iconText());
  if (!checkFile.exists())
  {
    // This should never happen since the checks in aboutToShowMenu should
    // prevent it, but just in case...
    qWarning() << "Error: file '" << actn->iconText()
               << "' does not exist.";
    return;
  }

  QString filename = actn->data().toString();
  if (SaveLoadStateReaction::loadState(filename))
  {
    // the above call will ensure that the file name moves to top of the list
    // since it calls pushStateFile() on success.
    return;
  }

  // remove the item from the recent state files list.
  pugi::xml_document settings;
  get_settings(settings);
  pugi::xml_node root = settings.root();
  for (pugi::xml_node node = root.child("State"); node;
       node = node.next_sibling("State"))
  {
    if (filename == node.attribute("filename").as_string())
    {
      root.remove_child(node);
      save_settings(settings);
      break;
    }
  }
}

}
<commit_msg>Don't remove file from recent files if user clicks 'Cancel'<commit_after>/******************************************************************************

  This source file is part of the tomviz project.

  Copyright Kitware, Inc.

  This source code is released under the New BSD License, (the "License").

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

******************************************************************************/
#include "RecentFilesMenu.h"

#include "ActiveObjects.h"
#include "DataSource.h"
#include "LoadDataReaction.h"
#include "pqPipelineSource.h"
#include "pqSettings.h"
#include "SaveLoadStateReaction.h"
#include "Utilities.h"
#include "vtkNew.h"
#include "vtkSmartPointer.h"
#include "vtkSMCoreUtilities.h"
#include "vtkSMParaViewPipelineController.h"
#include "vtkSMPropertyHelper.h"
#include "vtkSMSessionProxyManager.h"
#include "vtkSMSourceProxy.h"

#include <QMenu>
#include <QDebug>
#include <sstream>
#include <string>

namespace tomviz
{

static const int MAX_ITEMS = 10;

void get_settings(pugi::xml_document& doc)
{
  QSettings* settings = pqApplicationCore::instance()->settings();
  QString recent = settings->value("recentFiles").toString();
  if (recent.isEmpty() || !doc.load(recent.toUtf8().data()) || !doc.child("tomvizRecentFilesMenu"))
  {
    doc.append_child("tomvizRecentFilesMenu");
  }
}

void save_settings(pugi::xml_document &doc)
{
  // trim the list.
  pugi::xml_node root = doc.root();
  std::vector<pugi::xml_node> to_remove;
  int counter=0;
  for (pugi::xml_node node = root.child("DataReader"); node;
       node = node.next_sibling("DataReader"), counter++)
  {
    if (counter >= MAX_ITEMS)
    {
      to_remove.push_back(node);
    }
  }
  counter=0;
  for (pugi::xml_node node = root.child("State"); node;
       node = node.next_sibling("State"), counter++)
  {
    if (counter >= MAX_ITEMS)
    {
      to_remove.push_back(node);
    }
  }
  for (size_t cc = 0; cc < to_remove.size(); cc++)
  {
    root.remove_child(to_remove[cc]);
  }

  std::ostringstream stream;
  doc.save(stream);
  QSettings* settings = pqApplicationCore::instance()->settings();
  settings->setValue("recentFiles", stream.str().c_str());
}

//-------------------------------------------------------------------------
RecentFilesMenu::RecentFilesMenu(QMenu& menu, QObject* parentObject)
  : Superclass(parentObject)
{
  this->connect(&menu, SIGNAL(aboutToShow()), SLOT(aboutToShowMenu()));
}

//-------------------------------------------------------------------------
RecentFilesMenu::~RecentFilesMenu()
{
}

//-------------------------------------------------------------------------
void RecentFilesMenu::pushDataReader(vtkSMProxy* readerProxy)
{
  pugi::xml_document settings;
  get_settings(settings);

  pugi::xml_node root = settings.root();
  const char* pname = vtkSMCoreUtilities::GetFileNameProperty(readerProxy);
  if (pname)
  {
    const char* filename = vtkSMPropertyHelper(readerProxy,
                                               pname).GetAsString(0);
    for (pugi::xml_node node = root.child("DataReader"); node;
         node = node.next_sibling("DataReader"))
    {
      if (strcmp(node.attribute("filename0").as_string(""), filename) == 0)
      {
        root.remove_child(node);
        break;
      }
    }
    pugi::xml_node node = root.prepend_child("DataReader");
    node.append_attribute("filename0").set_value(filename);
    node.append_attribute("xmlgroup").set_value(readerProxy->GetXMLGroup());
    node.append_attribute("xmlname").set_value(readerProxy->GetXMLName());
    tomviz::serialize(readerProxy, node);

    save_settings(settings);
  }
}

//-------------------------------------------------------------------------
void RecentFilesMenu::pushStateFile(const QString& filename)
{
  pugi::xml_document settings;
  get_settings(settings);

  pugi::xml_node root = settings.root();
  for (pugi::xml_node node = root.child("State"); node;
       node = node.next_sibling("State"))
  {
    if (filename == node.attribute("filename").as_string(""))
    {
      root.remove_child(node);
      break;
    }
  }

  pugi::xml_node node = root.prepend_child("State");
  node.append_attribute("filename").set_value(filename.toLatin1().data());
  save_settings(settings);
}

//-------------------------------------------------------------------------
void RecentFilesMenu::aboutToShowMenu()
{
  QMenu* menu = qobject_cast<QMenu*>(this->sender());
  Q_ASSERT(menu);
  menu->clear();

  pugi::xml_document settings;
  get_settings(settings);

  pugi::xml_node root = settings.root();
  if (!root.child("DataReader") && !root.child("State"))
  {
    QAction* actn = menu->addAction("Empty");
    actn->setEnabled(false);
    return;
  }

  bool header_added = false;
  int index=0;
  for (pugi::xml_node node = root.child("DataReader"); node;
       node = node.next_sibling("DataReader"))
  {
    if (header_added == false)
    {
      QAction* actn = menu->addAction("Datasets");
      actn->setEnabled(false);
      header_added = true;
    }
    QFileInfo checkFile(node.attribute("filename0").as_string("<bug>"));
    if (checkFile.exists())
    {
      QAction* actn = menu->addAction(QIcon(":/pqWidgets/Icons/pqInspect22.png"),
        node.attribute("filename0").as_string("<bug>"));
      actn->setData(index);
      this->connect(actn, SIGNAL(triggered()), SLOT(dataSourceTriggered()));
    }
    index++;
  }

  header_added = false;
  for (pugi::xml_node node = root.child("State"); node;
       node = node.next_sibling("State"))
  {
    if (header_added == false)
    {
      QAction* actn = menu->addAction("State files");
      actn->setEnabled(false);
      header_added = true;
    }
    QFileInfo checkFile(node.attribute("filename").as_string("<bug>"));
    if (checkFile.exists())
    {
      QAction* actn = menu->addAction(QIcon(":/icons/tomviz.png"),
        node.attribute("filename").as_string("<bug>"));
      actn->setData(node.attribute("filename").as_string("<bug>"));
      this->connect(actn, SIGNAL(triggered()), SLOT(stateTriggered()));
    }
    index++;
  }
}

//-------------------------------------------------------------------------
void RecentFilesMenu::dataSourceTriggered()
{
  QAction* actn = qobject_cast<QAction*>(this->sender());
  Q_ASSERT(actn);

  QFileInfo checkFile(actn->iconText());
  if (!checkFile.exists())
  {
    // This should never happen since the checks in aboutToShowMenu should
    // prevent it, but just in case...
    qWarning() << "Error: file '" << actn->iconText()
               << "' does not exist.";
    return;
  }

  int index = actn->data().toInt();
  pugi::xml_document settings;
  get_settings(settings);
  pugi::xml_node root = settings.root();

  for (pugi::xml_node node = root.child("DataReader"); node;
       node = node.next_sibling("DataReader"), --index)
  {
    if (index == 0)
    {
      vtkSMSessionProxyManager* pxm = ActiveObjects::instance().proxyManager();
      vtkSmartPointer<vtkSMProxy> reader;
      reader.TakeReference(pxm->NewProxy(node.attribute("xmlgroup").as_string(),
                                         node.attribute("xmlname").as_string()));
      if (tomviz::deserialize(reader, node))
      {
        reader->UpdateVTKObjects();
        vtkSMSourceProxy::SafeDownCast(reader)->UpdatePipelineInformation();
        if (LoadDataReaction::createDataSource(reader))
        {
          // reorder the nodes to move the recently opened file to the top.
          root.prepend_copy(node);
          root.remove_child(node);
          save_settings(settings);
          return;
        }
        // If the user pressed 'Cancel' on the reader properties dialog,
        // don't remove the node
        return;
      }
      // failed to create reader, remove the node.
      root.remove_child(node);
      save_settings(settings);
      return;
    }
  }
}

//-------------------------------------------------------------------------
void RecentFilesMenu::stateTriggered()
{
  QAction* actn = qobject_cast<QAction*>(this->sender());
  Q_ASSERT(actn);

  QFileInfo checkFile(actn->iconText());
  if (!checkFile.exists())
  {
    // This should never happen since the checks in aboutToShowMenu should
    // prevent it, but just in case...
    qWarning() << "Error: file '" << actn->iconText()
               << "' does not exist.";
    return;
  }

  QString filename = actn->data().toString();
  if (SaveLoadStateReaction::loadState(filename))
  {
    // the above call will ensure that the file name moves to top of the list
    // since it calls pushStateFile() on success.
    return;
  }

  // remove the item from the recent state files list.
  pugi::xml_document settings;
  get_settings(settings);
  pugi::xml_node root = settings.root();
  for (pugi::xml_node node = root.child("State"); node;
       node = node.next_sibling("State"))
  {
    if (filename == node.attribute("filename").as_string())
    {
      root.remove_child(node);
      save_settings(settings);
      break;
    }
  }
}

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: iserver.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: svesik $ $Date: 2001-05-04 17:00:17 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#include "iparser.hxx"
#include "geninfo.hxx"
#include "appdef.hxx"
#include <stdio.h>

/*****************************************************************************/
#ifdef UNX
int main( int argc, char *argv[] )
#else
int _cdecl main( int argc, char *argv[] )
#endif
/*****************************************************************************/
{
    if ( argc == 1 ) {
        fprintf( stdout, "\ni_server.exe v2.0 (c) 2000\n\n" );
        fprintf( stdout, "Syntax:  i_server -i accesspath [-l] [-d database] \n" );
        fprintf( stdout, "Example: - i_server -i vcl364/settings/now\n" );
        fprintf( stdout, "           returns value of settings \"now\" of version \"vcl364\"\n" );
        fprintf( stdout, "         - i_server -i vcl364/settings -l\n" );
        fprintf( stdout, "           returns a list of all settings of version \"vcl364\"\n" );
    }
    else {
        BOOL bError = FALSE;
        BOOL bList = FALSE;
        ByteString sInfo( "" );
        ByteString sDataBase( GetDefStandList());

        BOOL bGetNow = FALSE;

        int nCount = 1;
        while (( nCount < argc ) &&
            ( !bError ))
        {
            if ( ByteString( argv[nCount] ).ToUpperAscii() == "-I" ) {
                // requestet info path
                nCount++;
                if( nCount < argc ) {
                    sInfo = ByteString( argv[nCount] );
                    nCount++;
                }
                else bError = TRUE;
            }
            else if ( ByteString( argv[nCount] ).ToUpperAscii() == "-D" ) {
                // requestet info path
                nCount++;
                if( nCount < argc ) {
                    sDataBase = ByteString( argv[nCount] );
                    nCount++;
                }
                else bError = TRUE;
            }
            else if ( ByteString( argv[nCount] ).ToUpperAscii() == "-L" ) {
                // request list of childs
                nCount++;
                bList = TRUE;
            }
            else if ( ByteString( argv[nCount] ).ToUpperAscii() == "-N" ) {
                // request list of childs
                nCount++;
                bGetNow = TRUE;
            }
            else {
                bError = TRUE;
            }
        }

        if ( !bError ) {
            InformationParser aParser( REPLACE_VARIABLES );
            ByteString sStandList( sDataBase );
            String s = String( sStandList, gsl_getSystemTextEncoding());
            GenericInformationList *pList = aParser.Execute( s );
            if ( !pList )
                return 1;

            if ( sInfo.Len()) {
                GenericInformation *pInfo = pList->GetInfo( sInfo, TRUE );

                if ( pInfo ) {
                    ByteString sValue( pInfo->GetValue());
                    // show the info and its value
                    fprintf( stdout, "%s %s\n", pInfo->GetBuffer(), sValue.GetBuffer());
                    if ( bList ) {
                        GenericInformationList *pList = pInfo->GetSubList();
                        if ( pList ) {
                            // show whole list of childs and their values
                            for( ULONG i = 0; i < pList->Count(); i++ ) {
                                GenericInformation *pInfo = pList->GetObject( i );
                                ByteString sValue( pInfo->GetValue());
                                fprintf( stdout, "    %s %s\n", pInfo->GetBuffer(), sValue.GetBuffer());
                            }
                        }
                    }
                    return 0;
                }
                return 1;
            }
            else {
                // show whole list of childs and their values
                for( ULONG i = 0; i < pList->Count(); i++ ) {
                    GenericInformation *pInfo = pList->GetObject( i );
                    if ( bGetNow ) {
                        ByteString sPath( "settings/now" );
                        GenericInformation *pSubInfo = pInfo->GetSubInfo( sPath, TRUE );
                        if ( pSubInfo && pSubInfo->GetValue() == "_TRUE" )
                            fprintf( stdout, "%s\n", pInfo->GetBuffer());
                    }
                    else {
                        ByteString sValue( pInfo->GetValue());
                        fprintf( stdout, "    %s %s\n", pInfo->GetBuffer(), sValue.GetBuffer());
                    }
                }
                return 0;
            }
        }
        else
            fprintf( stderr, "%s: Fehler in der Kommandozeile!", argv[0] );
            // command line arror !!!
    }

    return 1;
}

<commit_msg>INTEGRATION: CWS ooo19126 (1.2.418); FILE MERGED 2005/09/05 13:58:15 rt 1.2.418.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: iserver.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 13:29:49 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#include "iparser.hxx"
#include "geninfo.hxx"
#include "appdef.hxx"
#include <stdio.h>

/*****************************************************************************/
#ifdef UNX
int main( int argc, char *argv[] )
#else
int _cdecl main( int argc, char *argv[] )
#endif
/*****************************************************************************/
{
    if ( argc == 1 ) {
        fprintf( stdout, "\ni_server.exe v2.0 (c) 2000\n\n" );
        fprintf( stdout, "Syntax:  i_server -i accesspath [-l] [-d database] \n" );
        fprintf( stdout, "Example: - i_server -i vcl364/settings/now\n" );
        fprintf( stdout, "           returns value of settings \"now\" of version \"vcl364\"\n" );
        fprintf( stdout, "         - i_server -i vcl364/settings -l\n" );
        fprintf( stdout, "           returns a list of all settings of version \"vcl364\"\n" );
    }
    else {
        BOOL bError = FALSE;
        BOOL bList = FALSE;
        ByteString sInfo( "" );
        ByteString sDataBase( GetDefStandList());

        BOOL bGetNow = FALSE;

        int nCount = 1;
        while (( nCount < argc ) &&
            ( !bError ))
        {
            if ( ByteString( argv[nCount] ).ToUpperAscii() == "-I" ) {
                // requestet info path
                nCount++;
                if( nCount < argc ) {
                    sInfo = ByteString( argv[nCount] );
                    nCount++;
                }
                else bError = TRUE;
            }
            else if ( ByteString( argv[nCount] ).ToUpperAscii() == "-D" ) {
                // requestet info path
                nCount++;
                if( nCount < argc ) {
                    sDataBase = ByteString( argv[nCount] );
                    nCount++;
                }
                else bError = TRUE;
            }
            else if ( ByteString( argv[nCount] ).ToUpperAscii() == "-L" ) {
                // request list of childs
                nCount++;
                bList = TRUE;
            }
            else if ( ByteString( argv[nCount] ).ToUpperAscii() == "-N" ) {
                // request list of childs
                nCount++;
                bGetNow = TRUE;
            }
            else {
                bError = TRUE;
            }
        }

        if ( !bError ) {
            InformationParser aParser( REPLACE_VARIABLES );
            ByteString sStandList( sDataBase );
            String s = String( sStandList, gsl_getSystemTextEncoding());
            GenericInformationList *pList = aParser.Execute( s );
            if ( !pList )
                return 1;

            if ( sInfo.Len()) {
                GenericInformation *pInfo = pList->GetInfo( sInfo, TRUE );

                if ( pInfo ) {
                    ByteString sValue( pInfo->GetValue());
                    // show the info and its value
                    fprintf( stdout, "%s %s\n", pInfo->GetBuffer(), sValue.GetBuffer());
                    if ( bList ) {
                        GenericInformationList *pList = pInfo->GetSubList();
                        if ( pList ) {
                            // show whole list of childs and their values
                            for( ULONG i = 0; i < pList->Count(); i++ ) {
                                GenericInformation *pInfo = pList->GetObject( i );
                                ByteString sValue( pInfo->GetValue());
                                fprintf( stdout, "    %s %s\n", pInfo->GetBuffer(), sValue.GetBuffer());
                            }
                        }
                    }
                    return 0;
                }
                return 1;
            }
            else {
                // show whole list of childs and their values
                for( ULONG i = 0; i < pList->Count(); i++ ) {
                    GenericInformation *pInfo = pList->GetObject( i );
                    if ( bGetNow ) {
                        ByteString sPath( "settings/now" );
                        GenericInformation *pSubInfo = pInfo->GetSubInfo( sPath, TRUE );
                        if ( pSubInfo && pSubInfo->GetValue() == "_TRUE" )
                            fprintf( stdout, "%s\n", pInfo->GetBuffer());
                    }
                    else {
                        ByteString sValue( pInfo->GetValue());
                        fprintf( stdout, "    %s %s\n", pInfo->GetBuffer(), sValue.GetBuffer());
                    }
                }
                return 0;
            }
        }
        else
            fprintf( stderr, "%s: Fehler in der Kommandozeile!", argv[0] );
            // command line arror !!!
    }

    return 1;
}

<|endoftext|>


<commit_before>/*
    Copyright (C) 2008 Patrick Spendrin <ps_ml@gmx.de>

    This file is part of the KDE project

    This library is free software you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation either
    version 2 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    aint with this library see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include "KmlCoordinatesTagHandler.h"

#include <QtCore/QDebug>
#include <QtCore/QStringList>

#include "KmlElementDictionary.h"
#include "GeoDataPlacemark.h"
#include "GeoDataPoint.h"
#include "GeoDataLineString.h"
#include "GeoDataLinearRing.h"
#include "GeoDataMultiGeometry.h"
#include "GeoDataParser.h"
#include "global.h"

namespace Marble
{
namespace kml
{
KML_DEFINE_TAG_HANDLER( coordinates )

GeoNode* KmlcoordinatesTagHandler::parse( GeoParser& parser ) const
{
    Q_ASSERT( parser.isStartElement() && parser.isValidElement( kmlTag_coordinates ) );

    GeoStackItem parentItem = parser.parentElement();

    if( parentItem.nodeAs<GeoDataGeometry>() || parentItem.nodeAs<GeoDataPlacemark>() ) {
        QStringList  coordinatesLines = parser.readElementText().trimmed().split( ' ', QString::SkipEmptyParts );
        Q_FOREACH( const QString& line, coordinatesLines ) {
            QStringList coordinates = line.trimmed().split( ',' );
            if ( parentItem.nodeAs<GeoDataPlacemark>() ) {
                GeoDataPoint* coord = new GeoDataPoint();
                if ( coordinates.size() == 2 ) {
                    coord->set( DEG2RAD * coordinates.at( 0 ).toDouble(),
                                DEG2RAD * coordinates.at( 1 ).toDouble() );
                } else if( coordinates.size() == 3 ) {
                    coord->set( DEG2RAD * coordinates.at( 0 ).toDouble(),
                                DEG2RAD * coordinates.at( 1 ).toDouble(),
                                coordinates.at( 2 ).toDouble() );
                }
                parentItem.nodeAs<GeoDataPlacemark>()->setCoordinate( *coord );
                parentItem.nodeAs<GeoDataPlacemark>()->setGeometry( coord );
            } else {
                GeoDataCoordinates* coord = new GeoDataCoordinates();
                if ( coordinates.size() == 2 ) {
                    coord->set( DEG2RAD * coordinates.at( 0 ).toDouble(),
				DEG2RAD * coordinates.at( 1 ).toDouble() );
                } else if( coordinates.size() == 3 ) {
                    coord->set( DEG2RAD * coordinates.at( 0 ).toDouble(),
				DEG2RAD * coordinates.at( 1 ).toDouble(),
				coordinates.at( 2 ).toDouble() );
                }

                if ( parentItem.nodeAs<GeoDataLineString>() ) {
                    parentItem.nodeAs<GeoDataLineString>()->append( coord );
                } else if ( parentItem.nodeAs<GeoDataLinearRing>() ) {
                    parentItem.nodeAs<GeoDataLinearRing>()->append( coord );
                } else if ( parentItem.nodeAs<GeoDataMultiGeometry>() ) {
                    GeoDataPoint* point = new GeoDataPoint();
                    if ( coordinates.size() == 2 ) {
                        point->set( DEG2RAD * coordinates.at( 0 ).toDouble(),
				    DEG2RAD * coordinates.at( 1 ).toDouble() );
                    } else if ( coordinates.size() == 3 ) {
                        point->set( DEG2RAD * coordinates.at( 0 ).toDouble(),
				    DEG2RAD * coordinates.at( 1 ).toDouble(),
				    coordinates.at( 2 ).toDouble() );
                    }
                    parentItem.nodeAs<GeoDataMultiGeometry>()->append( point );
                } else {
                    // raise warning as coordinates out of valid parents found
                }
            }
#ifdef DEBUG_TAGS
        qDebug() << "Parsed <" << kmlTag_coordinates << "> containing: " << coordinates
                 << " parent item name: " << parentItem.qualifiedName().first;
#endif // DEBUG_TAGS
        }
    }
    return 0;
}

}
}
<commit_msg>break on all whitespaces<commit_after>/*
    Copyright (C) 2008 Patrick Spendrin <ps_ml@gmx.de>

    This file is part of the KDE project

    This library is free software you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation either
    version 2 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    aint with this library see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include "KmlCoordinatesTagHandler.h"

#include <QtCore/QDebug>
#include <QtCore/QStringList>
#include <QtCore/QRegExp>

#include "KmlElementDictionary.h"
#include "GeoDataPlacemark.h"
#include "GeoDataPoint.h"
#include "GeoDataLineString.h"
#include "GeoDataLinearRing.h"
#include "GeoDataMultiGeometry.h"
#include "GeoDataParser.h"
#include "global.h"

namespace Marble
{
namespace kml
{
KML_DEFINE_TAG_HANDLER( coordinates )

GeoNode* KmlcoordinatesTagHandler::parse( GeoParser& parser ) const
{
    Q_ASSERT( parser.isStartElement() && parser.isValidElement( kmlTag_coordinates ) );

    GeoStackItem parentItem = parser.parentElement();

    if( parentItem.nodeAs<GeoDataGeometry>() || parentItem.nodeAs<GeoDataPlacemark>() ) {
        QStringList  coordinatesLines = parser.readElementText().trimmed().split( QRegExp("\\s"), QString::SkipEmptyParts );
        Q_FOREACH( const QString& line, coordinatesLines ) {
            QStringList coordinates = line.trimmed().split( ',' );
            if ( parentItem.nodeAs<GeoDataPlacemark>() ) {
                GeoDataPoint* coord = new GeoDataPoint();
                if ( coordinates.size() == 2 ) {
                    coord->set( DEG2RAD * coordinates.at( 0 ).toDouble(),
                                DEG2RAD * coordinates.at( 1 ).toDouble() );
                } else if( coordinates.size() == 3 ) {
                    coord->set( DEG2RAD * coordinates.at( 0 ).toDouble(),
                                DEG2RAD * coordinates.at( 1 ).toDouble(),
                                coordinates.at( 2 ).toDouble() );
                }
                parentItem.nodeAs<GeoDataPlacemark>()->setCoordinate( *coord );
                parentItem.nodeAs<GeoDataPlacemark>()->setGeometry( coord );
            } else {
                GeoDataCoordinates* coord = new GeoDataCoordinates();
                if ( coordinates.size() == 2 ) {
                    coord->set( DEG2RAD * coordinates.at( 0 ).toDouble(),
				DEG2RAD * coordinates.at( 1 ).toDouble() );
                } else if( coordinates.size() == 3 ) {
                    coord->set( DEG2RAD * coordinates.at( 0 ).toDouble(),
				DEG2RAD * coordinates.at( 1 ).toDouble(),
				coordinates.at( 2 ).toDouble() );
                }

                if ( parentItem.nodeAs<GeoDataLineString>() ) {
                    parentItem.nodeAs<GeoDataLineString>()->append( coord );
                } else if ( parentItem.nodeAs<GeoDataLinearRing>() ) {
                    parentItem.nodeAs<GeoDataLinearRing>()->append( coord );
                } else if ( parentItem.nodeAs<GeoDataMultiGeometry>() ) {
                    GeoDataPoint* point = new GeoDataPoint();
                    if ( coordinates.size() == 2 ) {
                        point->set( DEG2RAD * coordinates.at( 0 ).toDouble(),
				    DEG2RAD * coordinates.at( 1 ).toDouble() );
                    } else if ( coordinates.size() == 3 ) {
                        point->set( DEG2RAD * coordinates.at( 0 ).toDouble(),
				    DEG2RAD * coordinates.at( 1 ).toDouble(),
				    coordinates.at( 2 ).toDouble() );
                    }
                    parentItem.nodeAs<GeoDataMultiGeometry>()->append( point );
                } else {
                    // raise warning as coordinates out of valid parents found
                }
            }
#ifdef DEBUG_TAGS
        qDebug() << "Parsed <" << kmlTag_coordinates << "> containing: " << coordinates
                 << " parent item name: " << parentItem.qualifiedName().first;
#endif // DEBUG_TAGS
        }
    }
    return 0;
}

}
}
<|endoftext|>


<commit_before>// ///////////////////////////////////////////////////////////////////////////
// tenh/applications/polynomial.hpp by Ted Nitz, created 2013/08/27
// Copyright Leap Motion Inc.
// ///////////////////////////////////////////////////////////////////////////

#ifndef TENH_APPLICATIONS_POLYNOMIAL_HPP_
#define TENH_APPLICATIONS_POLYNOMIAL_HPP_

#include "tenh/core.hpp"

#include <iostream>

#include "tenh/conceptual/symmetricpower.hpp"
#include "tenh/conceptual/vectorspace.hpp"
#include "tenh/implementation/vector.hpp"
#include "tenh/implementation/vee.hpp"

using Tenh::Uint32;

template <Uint32 DEGREE_, Uint32 DIMENSION_, typename Id_, typename Scalar_ = float>
struct MultivariatePolynomial
{
    typedef Tenh::BasedVectorSpace_c<Tenh::VectorSpace_c<Tenh::RealField,DIMENSION_,Id_>,Tenh::Basis_c<Id_> > VectorSpace;
    typedef Tenh::ImplementationOf_t<Scalar_, VectorSpace> Vector;
    typedef Tenh::ImplementationOf_t<Scalar_,Tenh::SymmetricPowerOfBasedVectorSpace_c<VectorSpace,DEGREE_> > Sym;
    // typedef typename Tenh::DualOf_f<Sym>::T SymDual;
   typedef Tenh::ImplementationOf_t<Scalar_,Tenh::SymmetricPowerOfBasedVectorSpace_c<typename Tenh::DualOf_f<VectorSpace>::T,DEGREE_> > SymDual;

    MultivariatePolynomial() : m_term(Scalar_(0)) {};
    MultivariatePolynomial(SymDual const &leading_term,  MultivariatePolynomial<DEGREE_-1,DIMENSION_,Id_,Scalar_> const &rest)
        : m_term(leading_term), m_body(rest) {};
    MultivariatePolynomial(SymDual const &leading_term)
        : m_term(leading_term), m_body() {};

    MultivariatePolynomial(MultivariatePolynomial const & other) : m_term(other.m_term), m_body(other.m_body) {};

    Scalar_ evaluate (Vector const &at) const
    {
        Tenh::AbstractIndex_c<'i'> i;
        std::cout << m_term << std::endl;
        return m_term(i)*OuterPowerOf(at)(i) + m_body.evaluate(at);
    }

    MultivariatePolynomial operator* (Scalar_ const &rhs) const
    {
        Tenh::AbstractIndex_c<'i'> i;
        SymDual term(Scalar_(0));
        term(i) = rhs*m_term(i);
        return MultivariatePolynomial(term, rhs*m_body);
    }
    MultivariatePolynomial operator- () const { return Scalar_(-1)*(*this); }

    MultivariatePolynomial add_eq(MultivariatePolynomial const &other) const
    {
        Tenh::AbstractIndex_c<'i'> i;
        SymDual term(Scalar_(0));
        term(i) = m_term(i) + other.m_term(i);
        return MultivariatePolynomial(term, m_body.add_eq(other.m_body));
    }
    template<Uint32 Other_Degree> MultivariatePolynomial add(MultivariatePolynomial<Other_Degree, DIMENSION_, Id_, Scalar_> const &other) const { return MultivariatePolynomial(m_term, m_body + other); }

    template<Uint32 Term_Degree>
    MultivariatePolynomial<Term_Degree + DEGREE_,DIMENSION_,Id_,Scalar_> monomial_multiply (Tenh::ImplementationOf_t<Scalar_,Tenh::SymmetricPowerOfBasedVectorSpace_c<typename Tenh::DualOf_f<VectorSpace>::T,Term_Degree> > const &monomial) const
    {
        typedef Tenh::SymmetricPowerOfBasedVectorSpace_c<typename Tenh::DualOf_f<VectorSpace>::T,Term_Degree + DEGREE_> ResultingTermType;
        Tenh::AbstractIndex_c<'i'> i;
        Tenh::AbstractIndex_c<'j'> j;
        Tenh::AbstractIndex_c<'k'> k;
        Tenh::ImplementationOf_t<Scalar_,ResultingTermType> result(Scalar_(0));
        result(i) = (m_term(j)*monomial(k)).bundle(j|k,ResultingTermType(),i);
        return MultivariatePolynomial<Term_Degree + DEGREE_, DIMENSION_, Id_, Scalar_>(result) + m_body.template monomial_multiply<Term_Degree>(monomial);
    }

private:
    SymDual m_term;
    MultivariatePolynomial<DEGREE_-1,DIMENSION_,Id_,Scalar_> m_body;

    Sym OuterPowerOf (Vector const &input) const
    {
        Sym result(Scalar_(1));

        for (typename Sym::ComponentIndex it; it.is_not_at_end(); ++it)
        {
            typename Sym::MultiIndex m = Sym::template bundle_index_map<typename Sym::MultiIndex::IndexTypeList, typename Sym::ComponentIndex>(it);
            for (Uint32 i = 0; i < Sym::MultiIndex::LENGTH; ++i)
            {
                result[it] *= input[typename Vector::ComponentIndex(m.value_of_index(i, Tenh::DONT_CHECK_RANGE))];
            }
        }
        std::cout << result << std::endl;
        return result;
    }

    template<Uint32,Uint32,typename,typename> friend struct MultivariatePolynomial;
    template<Uint32 DEG1, Uint32 DEG2, Uint32 DIM, typename Id, typename Scalar> friend
    MultivariatePolynomial<DEG1+DEG2,DIM,Id,Scalar> operator* (MultivariatePolynomial<DEG1,DIM,Id,Scalar> const &lhs, MultivariatePolynomial<DEG2,DIM,Id,Scalar> const &rhs);
};

template <Uint32 DIMENSION_, typename Id_, typename Scalar_>
struct MultivariatePolynomial<0,DIMENSION_,Id_,Scalar_>
{
    typedef Tenh::BasedVectorSpace_c<Tenh::VectorSpace_c<Tenh::RealField,DIMENSION_,Id_>,Tenh::Basis_c<Id_> > VectorSpace;
    typedef Tenh::ImplementationOf_t<Scalar_, VectorSpace> Vector;

    MultivariatePolynomial() : m_term(Scalar_(0)) {};
    MultivariatePolynomial(Scalar_ const &leading_term) : m_term(leading_term) {};
    MultivariatePolynomial(MultivariatePolynomial const & other) : m_term(other.m_term) {};

    Scalar_ evaluate (Vector const &at) const
    {
        std::cout << m_term << std::endl;
        return m_term;
    }

    MultivariatePolynomial operator- () const { return Scalar_(-1)*(*this); }
    MultivariatePolynomial operator* (Scalar_ const &rhs) const { return MultivariatePolynomial(rhs*m_term); }

    MultivariatePolynomial add_eq (MultivariatePolynomial const &other) const { return MultivariatePolynomial(m_term + other.m_term); }

    template<Uint32 Term_Degree>
    MultivariatePolynomial<Term_Degree, DIMENSION_, Id_, Scalar_> monomial_multiply (Tenh::ImplementationOf_t<Scalar_,Tenh::SymmetricPowerOfBasedVectorSpace_c<typename Tenh::DualOf_f<VectorSpace>::T,Term_Degree> > const &monomial) const
    {
        Tenh::AbstractIndex_c<'i'> i;
        Tenh::ImplementationOf_t<Scalar_,Tenh::SymmetricPowerOfBasedVectorSpace_c<typename Tenh::DualOf_f<VectorSpace>::T,Term_Degree> > term(Scalar_(0));
        term(i) = m_term*monomial(i);
        return MultivariatePolynomial<Term_Degree, DIMENSION_, Id_, Scalar_>(term);
    }

private:
    Scalar_ m_term;

    template<Uint32,Uint32,typename,typename> friend struct MultivariatePolynomial;
    template<Uint32 DEG1, Uint32 DEG2, Uint32 DIM, typename Id, typename Scalar> friend
    MultivariatePolynomial<DEG1+DEG2,DIM,Id,Scalar> operator* (MultivariatePolynomial<DEG1,DIM,Id,Scalar> const &lhs, MultivariatePolynomial<DEG2,DIM,Id,Scalar> const &rhs);
    template<Uint32 DEG, Uint32 DIM, typename Id, typename Scalar> friend
    MultivariatePolynomial<DEG,DIM,Id,Scalar> operator* (MultivariatePolynomial<0,DIM,Id,Scalar> const &lhs, MultivariatePolynomial<DEG,DIM,Id,Scalar> const &rhs);
};

// Non-member operator overloads
//    operator+
template<bool> struct Adder
{
    template<typename T, typename S>
    static T add (T const &lhs, S const &rhs) { return lhs.add(rhs); }
};

template<> struct Adder<false>
{
    template<typename T, typename S>
    static S add (T const &lhs, S const &rhs) { return rhs.add(lhs); }
};

template<Uint32 DEG1, Uint32 DEG2, Uint32 DIM, typename Id, typename Scalar>
MultivariatePolynomial<(DEG1>DEG2?DEG1:DEG2),DIM,Id,Scalar> operator+ (MultivariatePolynomial<DEG1,DIM,Id,Scalar> const &lhs, MultivariatePolynomial<DEG2,DIM,Id,Scalar> const &rhs)
{
    return Adder<(DEG1>DEG2)>::add(lhs,rhs);
}

template<Uint32 DEG, Uint32 DIM, typename Id, typename Scalar>
MultivariatePolynomial<DEG,DIM,Id,Scalar> operator+ (MultivariatePolynomial<DEG,DIM,Id,Scalar> const &lhs, MultivariatePolynomial<DEG,DIM,Id,Scalar> const &rhs)
{
    return lhs.add_eq(rhs);
}

//    operator-
template<Uint32 DEG1, Uint32 DEG2,  Uint32 DIM, typename Id, typename Scalar>
MultivariatePolynomial<(DEG1>DEG2?DEG1:DEG2),DIM,Id,Scalar> operator- (MultivariatePolynomial<DEG1,DIM,Id,Scalar> const &lhs, MultivariatePolynomial<DEG2,DIM,Id,Scalar> const &rhs)
{
    // Use operator+
    return lhs + (-rhs);
}

//    scalar operator*
template<Uint32 DEG, Uint32 DIM, typename Id, typename Scalar>
MultivariatePolynomial<DEG,DIM,Id,Scalar> operator* (Scalar const &lhs, MultivariatePolynomial<DEG,DIM,Id,Scalar> const &rhs)
{
    // Use the member version
    return rhs*lhs;
}

//    operator*
template<Uint32 DEG1, Uint32 DEG2, Uint32 DIM, typename Id, typename Scalar>
MultivariatePolynomial<DEG1+DEG2,DIM,Id,Scalar> operator* (MultivariatePolynomial<DEG1,DIM,Id,Scalar> const &lhs, MultivariatePolynomial<DEG2,DIM,Id,Scalar> const &rhs)
{
    return (rhs.template monomial_multiply<DEG1>(lhs.m_term)) + (lhs.m_body * rhs);
}

template<Uint32 DEG, Uint32 DIM, typename Id, typename Scalar>
MultivariatePolynomial<DEG,DIM,Id,Scalar> operator* (MultivariatePolynomial<0,DIM,Id,Scalar> const &lhs, MultivariatePolynomial<DEG,DIM,Id,Scalar> const &rhs)
{
    return lhs.m_term * rhs;
}

#endif // TENH_APPLICATIONS_POLYNOMIAL_HPP_
<commit_msg>Add some comments, move a couple functions out of the public interface, and make the binary operator- a member.<commit_after>// ///////////////////////////////////////////////////////////////////////////
// tenh/applications/polynomial.hpp by Ted Nitz, created 2013/08/27
// Copyright Leap Motion Inc.
// ///////////////////////////////////////////////////////////////////////////

#ifndef TENH_APPLICATIONS_POLYNOMIAL_HPP_
#define TENH_APPLICATIONS_POLYNOMIAL_HPP_

#include "tenh/core.hpp"

#include <iostream>

#include "tenh/conceptual/symmetricpower.hpp"
#include "tenh/conceptual/vectorspace.hpp"
#include "tenh/implementation/vector.hpp"
#include "tenh/implementation/vee.hpp"

using Tenh::Uint32;

template <Uint32 DEGREE_, Uint32 DIMENSION_, typename Id_, typename Scalar_ = float>
struct MultivariatePolynomial
{
    typedef Tenh::BasedVectorSpace_c<Tenh::VectorSpace_c<Tenh::RealField,DIMENSION_,Id_>,Tenh::Basis_c<Id_> > VectorSpace;
    typedef Tenh::ImplementationOf_t<Scalar_, VectorSpace> Vector;
    typedef Tenh::ImplementationOf_t<Scalar_,Tenh::SymmetricPowerOfBasedVectorSpace_c<VectorSpace,DEGREE_> > Sym;
    typedef typename Tenh::DualOf_f<Sym>::T SymDual;
    // typedef Tenh::ImplementationOf_t<Scalar_,Tenh::SymmetricPowerOfBasedVectorSpace_c<typename Tenh::DualOf_f<VectorSpace>::T,DEGREE_> > SymDual;

    MultivariatePolynomial() : m_term(Scalar_(0)) {};
    MultivariatePolynomial(SymDual const &leading_term,  MultivariatePolynomial<DEGREE_-1,DIMENSION_,Id_,Scalar_> const &rest)
        : m_term(leading_term), m_body(rest) {};
    MultivariatePolynomial(SymDual const &leading_term)
        : m_term(leading_term), m_body() {};

    MultivariatePolynomial(MultivariatePolynomial const & other) : m_term(other.m_term), m_body(other.m_body) {};

    Scalar_ evaluate (Vector const &at) const
    {
        Tenh::AbstractIndex_c<'i'> i;
        std::cout << m_term << std::endl;
        return m_term(i)*OuterPowerOf(at)(i) + m_body.evaluate(at);
    }

    // Member operators
    MultivariatePolynomial operator* (Scalar_ const &rhs) const
    {
        Tenh::AbstractIndex_c<'i'> i;
        SymDual term(Scalar_(0));
        term(i) = rhs*m_term(i);
        return MultivariatePolynomial(term, rhs*m_body);
    }
    MultivariatePolynomial operator- () const { return Scalar_(-1)*(*this); }

    template<Uint32 DEG>
    MultivariatePolynomial<(DEG>DEGREE_?DEG:DEGREE_),DIMENSION_,Id_,Scalar_> operator- (MultivariatePolynomial<DEG,DIMENSION_,Id_,Scalar_> const &rhs)
    {
        // Use operator+
        return *this + (-rhs);
    }

private:
    SymDual m_term;
    MultivariatePolynomial<DEGREE_-1,DIMENSION_,Id_,Scalar_> m_body;

    // Helper members for non-member operators.
    //    add is for adding a polynomial of lower degree to this polynomial
    template<Uint32 Other_Degree> MultivariatePolynomial add(MultivariatePolynomial<Other_Degree, DIMENSION_, Id_, Scalar_> const &other) const { return MultivariatePolynomial(m_term, m_body + other); }

    //    add_eq adds a polynomial of the same degree to this polynomial.
    MultivariatePolynomial add_eq(MultivariatePolynomial const &other) const
    {
        Tenh::AbstractIndex_c<'i'> i;
        SymDual term(Scalar_(0));
        term(i) = m_term(i) + other.m_term(i);
        return MultivariatePolynomial(term, m_body.add_eq(other.m_body));
    }

    template<Uint32 Term_Degree>
    MultivariatePolynomial<Term_Degree + DEGREE_,DIMENSION_,Id_,Scalar_> monomial_multiply (Tenh::ImplementationOf_t<Scalar_,Tenh::SymmetricPowerOfBasedVectorSpace_c<typename Tenh::DualOf_f<VectorSpace>::T,Term_Degree> > const &monomial) const
    {
        typedef Tenh::SymmetricPowerOfBasedVectorSpace_c<typename Tenh::DualOf_f<VectorSpace>::T,Term_Degree + DEGREE_> ResultingTermType;
        Tenh::AbstractIndex_c<'i'> i;
        Tenh::AbstractIndex_c<'j'> j;
        Tenh::AbstractIndex_c<'k'> k;
        Tenh::ImplementationOf_t<Scalar_,ResultingTermType> result(Scalar_(0));
        result(i) = (m_term(j)*monomial(k)).bundle(j|k,ResultingTermType(),i);
        return MultivariatePolynomial<Term_Degree + DEGREE_, DIMENSION_, Id_, Scalar_>(result) + m_body.template monomial_multiply<Term_Degree>(monomial);
    }

    // This should probably be a function in tensor heaven somewhere.
    Sym OuterPowerOf (Vector const &input) const
    {
        Sym result(Scalar_(1));

        for (typename Sym::ComponentIndex it; it.is_not_at_end(); ++it)
        {
            typename Sym::MultiIndex m = Sym::template bundle_index_map<typename Sym::MultiIndex::IndexTypeList, typename Sym::ComponentIndex>(it);
            for (Uint32 i = 0; i < Sym::MultiIndex::LENGTH; ++i)
            {
                result[it] *= input[typename Vector::ComponentIndex(m.value_of_index(i, Tenh::DONT_CHECK_RANGE))];
            }
        }
        std::cout << result << std::endl;
        return result;
    }

    template<Uint32,Uint32,typename,typename> friend struct MultivariatePolynomial;
    template<bool> friend struct Adder;
    template<Uint32 DEG, Uint32 DIM, typename Id, typename Scalar> friend
    MultivariatePolynomial<DEG,DIM,Id,Scalar> operator+ (MultivariatePolynomial<DEG,DIM,Id,Scalar> const &lhs, MultivariatePolynomial<DEG,DIM,Id,Scalar> const &rhs);
    template<Uint32 DEG1, Uint32 DEG2, Uint32 DIM, typename Id, typename Scalar> friend
    MultivariatePolynomial<DEG1+DEG2,DIM,Id,Scalar> operator* (MultivariatePolynomial<DEG1,DIM,Id,Scalar> const &lhs, MultivariatePolynomial<DEG2,DIM,Id,Scalar> const &rhs);
};

template <Uint32 DIMENSION_, typename Id_, typename Scalar_>
struct MultivariatePolynomial<0,DIMENSION_,Id_,Scalar_>
{
    typedef Tenh::BasedVectorSpace_c<Tenh::VectorSpace_c<Tenh::RealField,DIMENSION_,Id_>,Tenh::Basis_c<Id_> > VectorSpace;
    typedef Tenh::ImplementationOf_t<Scalar_, VectorSpace> Vector;

    MultivariatePolynomial() : m_term(Scalar_(0)) {};
    MultivariatePolynomial(Scalar_ const &leading_term) : m_term(leading_term) {};
    MultivariatePolynomial(MultivariatePolynomial const & other) : m_term(other.m_term) {};

    Scalar_ evaluate (Vector const &at) const
    {
        std::cout << m_term << std::endl;
        return m_term;
    }

    MultivariatePolynomial operator- () const { return Scalar_(-1)*(*this); }
    template<Uint32 DEG>
    MultivariatePolynomial<DEG,DIMENSION_,Id_,Scalar_> operator- (MultivariatePolynomial<DEG,DIMENSION_,Id_,Scalar_> const &rhs)
    {
        // Use operator+
        return *this + (-rhs);
    }
    MultivariatePolynomial operator* (Scalar_ const &rhs) const { return MultivariatePolynomial(rhs*m_term); }

private:
    Scalar_ m_term;

    //    There is no lower degree possible, so we only need add_eq here.
    MultivariatePolynomial add_eq (MultivariatePolynomial const &other) const { return MultivariatePolynomial(m_term + other.m_term); }

    template<Uint32 Term_Degree>
    MultivariatePolynomial<Term_Degree, DIMENSION_, Id_, Scalar_> monomial_multiply (Tenh::ImplementationOf_t<Scalar_,Tenh::SymmetricPowerOfBasedVectorSpace_c<typename Tenh::DualOf_f<VectorSpace>::T,Term_Degree> > const &monomial) const
    {
        Tenh::AbstractIndex_c<'i'> i;
        Tenh::ImplementationOf_t<Scalar_,Tenh::SymmetricPowerOfBasedVectorSpace_c<typename Tenh::DualOf_f<VectorSpace>::T,Term_Degree> > term(Scalar_(0));
        term(i) = m_term*monomial(i);
        return MultivariatePolynomial<Term_Degree, DIMENSION_, Id_, Scalar_>(term);
    }

    template<Uint32,Uint32,typename,typename> friend struct MultivariatePolynomial;
    template<bool> friend struct Adder;
    template<Uint32 DEG, Uint32 DIM, typename Id, typename Scalar> friend
    MultivariatePolynomial<DEG,DIM,Id,Scalar> operator+ (MultivariatePolynomial<DEG,DIM,Id,Scalar> const &lhs, MultivariatePolynomial<DEG,DIM,Id,Scalar> const &rhs);
    template<Uint32 DEG1, Uint32 DEG2, Uint32 DIM, typename Id, typename Scalar> friend
    MultivariatePolynomial<DEG1+DEG2,DIM,Id,Scalar> operator* (MultivariatePolynomial<DEG1,DIM,Id,Scalar> const &lhs, MultivariatePolynomial<DEG2,DIM,Id,Scalar> const &rhs);
    template<Uint32 DEG, Uint32 DIM, typename Id, typename Scalar> friend
    MultivariatePolynomial<DEG,DIM,Id,Scalar> operator* (MultivariatePolynomial<0,DIM,Id,Scalar> const &lhs, MultivariatePolynomial<DEG,DIM,Id,Scalar> const &rhs);
};

// Non-member operator overloads. These exist because they must be partially specalized, or because they cannot be written as member operator overloads.
//    operator+
template<bool> struct Adder
{
    template<typename T, typename S>
    static T add (T const &lhs, S const &rhs) { return lhs.add(rhs); }
};

template<> struct Adder<false>
{
    template<typename T, typename S>
    static S add (T const &lhs, S const &rhs) { return rhs.add(lhs); }
};

template<Uint32 DEG1, Uint32 DEG2, Uint32 DIM, typename Id, typename Scalar>
MultivariatePolynomial<(DEG1>DEG2?DEG1:DEG2),DIM,Id,Scalar> operator+ (MultivariatePolynomial<DEG1,DIM,Id,Scalar> const &lhs, MultivariatePolynomial<DEG2,DIM,Id,Scalar> const &rhs)
{
    return Adder<(DEG1>DEG2)>::add(lhs,rhs);
}

template<Uint32 DEG, Uint32 DIM, typename Id, typename Scalar>
MultivariatePolynomial<DEG,DIM,Id,Scalar> operator+ (MultivariatePolynomial<DEG,DIM,Id,Scalar> const &lhs, MultivariatePolynomial<DEG,DIM,Id,Scalar> const &rhs)
{
    return lhs.add_eq(rhs);
}

//    scalar operator*
template<Uint32 DEG, Uint32 DIM, typename Id, typename Scalar>
MultivariatePolynomial<DEG,DIM,Id,Scalar> operator* (Scalar const &lhs, MultivariatePolynomial<DEG,DIM,Id,Scalar> const &rhs)
{
    // Use the member version
    return rhs*lhs;
}

//    operator*
template<Uint32 DEG1, Uint32 DEG2, Uint32 DIM, typename Id, typename Scalar>
MultivariatePolynomial<DEG1+DEG2,DIM,Id,Scalar> operator* (MultivariatePolynomial<DEG1,DIM,Id,Scalar> const &lhs, MultivariatePolynomial<DEG2,DIM,Id,Scalar> const &rhs)
{
    return (rhs.template monomial_multiply<DEG1>(lhs.m_term)) + (lhs.m_body * rhs);
}

template<Uint32 DEG, Uint32 DIM, typename Id, typename Scalar>
MultivariatePolynomial<DEG,DIM,Id,Scalar> operator* (MultivariatePolynomial<0,DIM,Id,Scalar> const &lhs, MultivariatePolynomial<DEG,DIM,Id,Scalar> const &rhs)
{
    return lhs.m_term * rhs;
}

#endif // TENH_APPLICATIONS_POLYNOMIAL_HPP_
<|endoftext|>