<commit_before>// -------------------------------------------------------------------------
//    @FileName         :    NFCProperty.cpp
//    @Author           :    LvSheng.Huang
//    @Date             :    2012-03-01
//    @Module           :    NFCProperty
//
// -------------------------------------------------------------------------

#include "NFCProperty.h"
#include <complex>

NFCProperty::NFCProperty()
{
    mbPublic = false;
    mbPrivate = false;
    mbSave = false;
    mSelf = NFGUID();
    eType = TDATA_UNKNOWN;

    msPropertyName = "";
}

NFCProperty::NFCProperty(const NFGUID& self, const std::string& strPropertyName, const TDATA_TYPE varType, bool bPublic,  bool bPrivate,  bool bSave, const std::string& strRelationValue)
{

    mbPublic = bPublic;
    mbPrivate = bPrivate;
    mbSave = bSave;
    mSelf = self;

    msPropertyName = strPropertyName;
    mstrRelationValue = strRelationValue;
    eType = varType;
}

NFCProperty::~NFCProperty()
{
    for (TPROPERTYCALLBACKEX::iterator iter = mtPropertyCallback.begin(); iter != mtPropertyCallback.end(); ++iter)
    {
        iter->reset();
    }

    mtPropertyCallback.clear();
    mxData.reset();
}

void NFCProperty::SetValue(const NFIDataList::TData& TData)
{
    if (eType != TData.GetType())
    {
        return;
    }

    if (!mxData.get())
    {
        if (!TData.IsNullValue())
        {
            return;
        }

        mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TData));
    }

    NFCDataList::TData oldValue;
    oldValue = *mxData;

    mxData->variantData = TData.variantData;

    NFCDataList::TData newValue;
    newValue = *mxData;

    OnEventHandler(oldValue , newValue);
}

void NFCProperty::SetValue(const NFIProperty* pProperty)
{
    SetValue(pProperty->GetValue());
}

const NFIDataList::TData& NFCProperty::GetValue() const
{
    if (mxData.get())
    {
        return *mxData;
    }

    return NULL_TDATA;
}

const std::string&  NFCProperty::GetKey() const
{
    return msPropertyName;
}

const bool NFCProperty::GetSave() const
{
    return mbSave;
}

const bool NFCProperty::GetPublic() const
{
    return mbPublic;
}

const bool NFCProperty::GetPrivate() const
{
    return mbPrivate;
}

const std::string& NFCProperty::GetRelationValue() const
{
    return mstrRelationValue;
}

void NFCProperty::SetSave(bool bSave)
{
    mbSave = bSave;
}

void NFCProperty::SetPublic(bool bPublic)
{
    mbPublic = bPublic;
}

void NFCProperty::SetPrivate(bool bPrivate)
{
    mbPrivate = bPrivate;
}

void NFCProperty::SetRelationValue(const std::string& strRelationValue)
{
    mstrRelationValue = strRelationValue;
}

NFINT64 NFCProperty::GetInt() const
{
    if (!mxData.get())
    {
        return 0;
    }

    return mxData->GetInt();
}

double NFCProperty::GetFloat() const
{
    if (!mxData.get())
    {
        return 0.0;
    }

    return mxData->GetFloat();
}

const std::string& NFCProperty::GetString() const
{
    if (!mxData.get())
    {
        return NULL_STR;
    }

    return mxData->GetString();
}

const NFGUID& NFCProperty::GetObject() const
{
    if (!mxData.get())
    {
        return NULL_OBJECT;
    }

    return mxData->GetObject();
}

void NFCProperty::RegisterCallback(const PROPERTY_EVENT_FUNCTOR_PTR& cb)
{
    mtPropertyCallback.push_back(cb);
}

int NFCProperty::OnEventHandler(const NFIDataList::TData& oldVar, const NFIDataList::TData& newVar)
{
    if (mtPropertyCallback.size() <= 0)
    {
        return 0;
    }

    TPROPERTYCALLBACKEX::iterator it = mtPropertyCallback.begin();
    TPROPERTYCALLBACKEX::iterator end = mtPropertyCallback.end();
    for (it; it != end; ++it)
    {
        //NFIDataList:OLDֵNEWֵ, ARG(pKernel,self)
        PROPERTY_EVENT_FUNCTOR_PTR& pFunPtr = *it;
        PROPERTY_EVENT_FUNCTOR* pFunc = pFunPtr.get();
        int nTemRet = pFunc->operator()(mSelf, msPropertyName, oldVar, newVar);
    }

    return 0;
}

bool NFCProperty::SetInt(const NFINT64 value)
{
    if (eType != TDATA_INT)
    {
        return false;
    }

    if (!mxData.get())
    {
        //ǿվΪûݣûݵľͲ
        if (0 == value)
        {
            return false;
        }

        mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_INT));
        mxData->SetInt(0);
    }

    if (value == mxData->GetInt())
    {
        return false;
    }

    NFCDataList::TData oldValue;
    oldValue = *mxData;

    mxData->SetInt(value);

    OnEventHandler(oldValue, *mxData);

    return true;
}

bool NFCProperty::SetFloat(const double value)
{
    if (eType != TDATA_FLOAT)
    {
        return false;
    }

    if (!mxData.get())
    {
        //ǿվΪûݣûݵľͲ
        if (std::abs(value) < 0.001)
        {
            return false;
        }

        mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_FLOAT));
        mxData->SetFloat(0.0);
    }

    if (value - mxData->GetFloat() < 0.001)
    {
        return false;
    }

    NFCDataList::TData oldValue;
    oldValue = *mxData;

    mxData->SetFloat(value);

    OnEventHandler(oldValue, *mxData);

    return true;
}

bool NFCProperty::SetString(const std::string& value)
{
    if (eType != TDATA_STRING)
    {
        return false;
    }

    if (!mxData.get())
    {
        //ǿվΪûݣûݵľͲ
        if (value.empty())
        {
            return false;
        }

        mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_STRING));
        mxData->SetString(NULL_STR);
    }

    if (value == mxData->GetString())
    {
        return false;
    }

    NFCDataList::TData oldValue;
    oldValue = *mxData;

    mxData->SetString(value);

    OnEventHandler(oldValue, *mxData);

    return true;
}

bool NFCProperty::SetObject(const NFGUID& value)
{
    if (eType != TDATA_OBJECT)
    {
        return false;
    }

    if (!mxData.get())
    {
        //ǿվΪûݣûݵľͲ
        if (value.IsNull())
        {
            return false;
        }

        mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_OBJECT));
        mxData->SetObject(NFGUID());

    }

    if (value == mxData->GetObject())
    {
        return false;
    }

    NFCDataList::TData oldValue;
    oldValue = *mxData;

    mxData->SetObject(value);

    OnEventHandler(oldValue , *mxData);

    return true;
}

bool NFCProperty::Changed() const
{
    return GetValue().IsNullValue();
}

const TDATA_TYPE NFCProperty::GetType() const
{
    return eType;
}

const bool NFCProperty::GeUsed() const
{
    if (mxData.get())
    {
        return true;
    }

    return false;
}

std::string NFCProperty::ToString()
{
    std::string strData;
    const TDATA_TYPE eType = GetType();
    switch (eType)
    {
        case TDATA_INT:
            strData = lexical_cast<std::string> (GetInt());
            break;
        case TDATA_FLOAT:
            strData = lexical_cast<std::string> (GetFloat());
            break;
        case TDATA_STRING:
            strData = GetString();
            break;
		case TDATA_OBJECT:
            strData = GetObject().ToString();
            break;
        default:
            strData = NULL_STR;
            break;
    }

    return strData;
}

bool NFCProperty::FromString(const std::string& strData)
{
    const TDATA_TYPE eType = GetType();
    bool bRet = false;
    switch (eType)
    {
        case TDATA_INT:
        {
            NFINT64  nValue = 0;
            bRet = NF_StrTo(strData, nValue);
            SetInt(nValue);
        }
        break;

        case TDATA_FLOAT:
        {
            double  dValue = 0;
            bRet = NF_StrTo(strData, dValue);
            SetFloat(dValue);
        }
        break;

        case TDATA_STRING:
        {
            SetString(strData);
            bRet = true;
        }
        break;
        case TDATA_OBJECT:
        {
            NFGUID xID;

            bRet = xID.FromString(strData);
            SetObject(xID);
        }
        break;
        default:
            break;
    }

    return bRet;
}

bool NFCProperty::DeSerialization()
{
    bool bRet = false;

    const TDATA_TYPE eType = GetType();
    if(eType == TDATA_STRING)
    {
        NFCDataList xDataList;
        const std::string& strData = mxData->GetString();

        xDataList.Split(strData.c_str(), ";")
        for(int i = 0; i < xDataList.GetCount(); ++i)
        {
            if(nullptr == mxEmbeddedList)
            {
                mxEmbeddedList = NF_SHARE_PTR<NFList<std::string>>(NF_NEW NFList<std::string>());
            }
            else
            {
                mxEmbeddedList->ClearAll();
            }

            if(xDataList.String(i).empty())
            {
                NFASSERT(0, strData, __FILE__, __FUNCTION__);
            }

            mxEmbeddedList->Add(xDataList.String(i));
        }

        if(nullptr != mxEmbeddedList && mxEmbeddedList->Count() > 0)
        {
            std::string strTemData;
            for(bool bListRet = mxEmbeddedList->First(strTemData); bListRet == true; bListRet = mxEmbeddedList->Next(strTemData))
            {
                NFCDataList xTemDataList;
                xTemDataList.Split(strTemData.c_str(), ",")
                if(xTemDataList.GetCount() > 0)
                {
                    if (xTemDataList.GetCount() != 2)
                    {
                        NFASSERT(0, strTemData, __FILE__, __FUNCTION__);
                    }

                    const std::string& strKey = xTemDataList.String(0);
                    const std::string& strValue = xTemDataList.String(0);

                    if(strKey.empty() || strValue.empty())
                    {
                        NFASSERT(0, strTemData, __FILE__, __FUNCTION__);
                    }

                    if(nullptr == mxEmbeddedMap)
                    {
                        mxEmbeddedMap = NF_SHARE_PTR<NFMapEx<std::string, std::string>>(NF_NEW NFMapEx<std::string, std::string>());
                    }
                    else
                    {
                        mxEmbeddedMap->ClearAll();
                    }

                    mxEmbeddedMap->AddElement(strKey, NF_SHARE_PTR<std::string>(NF_NEW std::string(strValue)))
                }
            }

            bRet = true;
        }
    }

    return bRet;
}

const NF_SHARE_PTR<NFList<std::string>> NFCProperty::GetEmbeddedList() const
{
    return this->mxEmbeddedList;
}

const NF_SHARE_PTR<NFMapEx<std::string, std::string>> NFCProperty::GetEmbeddedMap() const
{
    return this->mxEmbeddedMap;
}
<commit_msg>fixed for compile<commit_after>// -------------------------------------------------------------------------
//    @FileName         :    NFCProperty.cpp
//    @Author           :    LvSheng.Huang
//    @Date             :    2012-03-01
//    @Module           :    NFCProperty
//
// -------------------------------------------------------------------------

#include "NFCProperty.h"
#include <complex>

NFCProperty::NFCProperty()
{
    mbPublic = false;
    mbPrivate = false;
    mbSave = false;
    mSelf = NFGUID();
    eType = TDATA_UNKNOWN;

    msPropertyName = "";
}

NFCProperty::NFCProperty(const NFGUID& self, const std::string& strPropertyName, const TDATA_TYPE varType, bool bPublic,  bool bPrivate,  bool bSave, const std::string& strRelationValue)
{

    mbPublic = bPublic;
    mbPrivate = bPrivate;
    mbSave = bSave;
    mSelf = self;

    msPropertyName = strPropertyName;
    mstrRelationValue = strRelationValue;
    eType = varType;
}

NFCProperty::~NFCProperty()
{
    for (TPROPERTYCALLBACKEX::iterator iter = mtPropertyCallback.begin(); iter != mtPropertyCallback.end(); ++iter)
    {
        iter->reset();
    }

    mtPropertyCallback.clear();
    mxData.reset();
}

void NFCProperty::SetValue(const NFIDataList::TData& TData)
{
    if (eType != TData.GetType())
    {
        return;
    }

    if (!mxData.get())
    {
        if (!TData.IsNullValue())
        {
            return;
        }

        mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TData));
    }

    NFCDataList::TData oldValue;
    oldValue = *mxData;

    mxData->variantData = TData.variantData;

    NFCDataList::TData newValue;
    newValue = *mxData;

    OnEventHandler(oldValue , newValue);
}

void NFCProperty::SetValue(const NFIProperty* pProperty)
{
    SetValue(pProperty->GetValue());
}

const NFIDataList::TData& NFCProperty::GetValue() const
{
    if (mxData.get())
    {
        return *mxData;
    }

    return NULL_TDATA;
}

const std::string&  NFCProperty::GetKey() const
{
    return msPropertyName;
}

const bool NFCProperty::GetSave() const
{
    return mbSave;
}

const bool NFCProperty::GetPublic() const
{
    return mbPublic;
}

const bool NFCProperty::GetPrivate() const
{
    return mbPrivate;
}

const std::string& NFCProperty::GetRelationValue() const
{
    return mstrRelationValue;
}

void NFCProperty::SetSave(bool bSave)
{
    mbSave = bSave;
}

void NFCProperty::SetPublic(bool bPublic)
{
    mbPublic = bPublic;
}

void NFCProperty::SetPrivate(bool bPrivate)
{
    mbPrivate = bPrivate;
}

void NFCProperty::SetRelationValue(const std::string& strRelationValue)
{
    mstrRelationValue = strRelationValue;
}

NFINT64 NFCProperty::GetInt() const
{
    if (!mxData.get())
    {
        return 0;
    }

    return mxData->GetInt();
}

double NFCProperty::GetFloat() const
{
    if (!mxData.get())
    {
        return 0.0;
    }

    return mxData->GetFloat();
}

const std::string& NFCProperty::GetString() const
{
    if (!mxData.get())
    {
        return NULL_STR;
    }

    return mxData->GetString();
}

const NFGUID& NFCProperty::GetObject() const
{
    if (!mxData.get())
    {
        return NULL_OBJECT;
    }

    return mxData->GetObject();
}

void NFCProperty::RegisterCallback(const PROPERTY_EVENT_FUNCTOR_PTR& cb)
{
    mtPropertyCallback.push_back(cb);
}

int NFCProperty::OnEventHandler(const NFIDataList::TData& oldVar, const NFIDataList::TData& newVar)
{
    if (mtPropertyCallback.size() <= 0)
    {
        return 0;
    }

    TPROPERTYCALLBACKEX::iterator it = mtPropertyCallback.begin();
    TPROPERTYCALLBACKEX::iterator end = mtPropertyCallback.end();
    for (it; it != end; ++it)
    {
        //NFIDataList:OLDֵNEWֵ, ARG(pKernel,self)
        PROPERTY_EVENT_FUNCTOR_PTR& pFunPtr = *it;
        PROPERTY_EVENT_FUNCTOR* pFunc = pFunPtr.get();
        int nTemRet = pFunc->operator()(mSelf, msPropertyName, oldVar, newVar);
    }

    return 0;
}

bool NFCProperty::SetInt(const NFINT64 value)
{
    if (eType != TDATA_INT)
    {
        return false;
    }

    if (!mxData.get())
    {
        //ǿվΪûݣûݵľͲ
        if (0 == value)
        {
            return false;
        }

        mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_INT));
        mxData->SetInt(0);
    }

    if (value == mxData->GetInt())
    {
        return false;
    }

    NFCDataList::TData oldValue;
    oldValue = *mxData;

    mxData->SetInt(value);

    OnEventHandler(oldValue, *mxData);

    return true;
}

bool NFCProperty::SetFloat(const double value)
{
    if (eType != TDATA_FLOAT)
    {
        return false;
    }

    if (!mxData.get())
    {
        //ǿվΪûݣûݵľͲ
        if (std::abs(value) < 0.001)
        {
            return false;
        }

        mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_FLOAT));
        mxData->SetFloat(0.0);
    }

    if (value - mxData->GetFloat() < 0.001)
    {
        return false;
    }

    NFCDataList::TData oldValue;
    oldValue = *mxData;

    mxData->SetFloat(value);

    OnEventHandler(oldValue, *mxData);

    return true;
}

bool NFCProperty::SetString(const std::string& value)
{
    if (eType != TDATA_STRING)
    {
        return false;
    }

    if (!mxData.get())
    {
        //ǿվΪûݣûݵľͲ
        if (value.empty())
        {
            return false;
        }

        mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_STRING));
        mxData->SetString(NULL_STR);
    }

    if (value == mxData->GetString())
    {
        return false;
    }

    NFCDataList::TData oldValue;
    oldValue = *mxData;

    mxData->SetString(value);

    OnEventHandler(oldValue, *mxData);

    return true;
}

bool NFCProperty::SetObject(const NFGUID& value)
{
    if (eType != TDATA_OBJECT)
    {
        return false;
    }

    if (!mxData.get())
    {
        //ǿվΪûݣûݵľͲ
        if (value.IsNull())
        {
            return false;
        }

        mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_OBJECT));
        mxData->SetObject(NFGUID());

    }

    if (value == mxData->GetObject())
    {
        return false;
    }

    NFCDataList::TData oldValue;
    oldValue = *mxData;

    mxData->SetObject(value);

    OnEventHandler(oldValue , *mxData);

    return true;
}

bool NFCProperty::Changed() const
{
    return GetValue().IsNullValue();
}

const TDATA_TYPE NFCProperty::GetType() const
{
    return eType;
}

const bool NFCProperty::GeUsed() const
{
    if (mxData.get())
    {
        return true;
    }

    return false;
}

std::string NFCProperty::ToString()
{
    std::string strData;
    const TDATA_TYPE eType = GetType();
    switch (eType)
    {
        case TDATA_INT:
            strData = lexical_cast<std::string> (GetInt());
            break;
        case TDATA_FLOAT:
            strData = lexical_cast<std::string> (GetFloat());
            break;
        case TDATA_STRING:
            strData = GetString();
            break;
		case TDATA_OBJECT:
            strData = GetObject().ToString();
            break;
        default:
            strData = NULL_STR;
            break;
    }

    return strData;
}

bool NFCProperty::FromString(const std::string& strData)
{
    const TDATA_TYPE eType = GetType();
    bool bRet = false;
    switch (eType)
    {
        case TDATA_INT:
        {
            NFINT64  nValue = 0;
            bRet = NF_StrTo(strData, nValue);
            SetInt(nValue);
        }
        break;

        case TDATA_FLOAT:
        {
            double  dValue = 0;
            bRet = NF_StrTo(strData, dValue);
            SetFloat(dValue);
        }
        break;

        case TDATA_STRING:
        {
            SetString(strData);
            bRet = true;
        }
        break;
        case TDATA_OBJECT:
        {
            NFGUID xID;

            bRet = xID.FromString(strData);
            SetObject(xID);
        }
        break;
        default:
            break;
    }

    return bRet;
}

bool NFCProperty::DeSerialization()
{
    bool bRet = false;

    const TDATA_TYPE eType = GetType();
    if (eType == TDATA_STRING)
    {
        NFCDataList xDataList;
        const std::string& strData = mxData->GetString();

        xDataList.Split(strData.c_str(), ";");
        for (int i = 0; i < xDataList.GetCount(); ++i)
        {
            if (nullptr == mxEmbeddedList)
            {
                mxEmbeddedList = NF_SHARE_PTR<NFList<std::string>>(NF_NEW NFList<std::string>());
            }
            else
            {
                mxEmbeddedList->ClearAll();
            }

            if(xDataList.String(i).empty())
            {
                NFASSERT(0, strData, __FILE__, __FUNCTION__);
            }

            mxEmbeddedList->Add(xDataList.String(i));
        }

        if (nullptr != mxEmbeddedList && mxEmbeddedList->Count() > 0)
        {
            std::string strTemData;
            for (bool bListRet = mxEmbeddedList->First(strTemData); bListRet == true; bListRet = mxEmbeddedList->Next(strTemData))
            {
                NFCDataList xTemDataList;
                xTemDataList.Split(strTemData.c_str(), ",");
                if (xTemDataList.GetCount() > 0)
                {
                    if (xTemDataList.GetCount() != 2)
                    {
                        NFASSERT(0, strTemData, __FILE__, __FUNCTION__);
                    }

                    const std::string& strKey = xTemDataList.String(0);
                    const std::string& strValue = xTemDataList.String(0);

                    if (strKey.empty() || strValue.empty())
                    {
                        NFASSERT(0, strTemData, __FILE__, __FUNCTION__);
                    }

                    if (nullptr == mxEmbeddedMap)
                    {
                        mxEmbeddedMap = NF_SHARE_PTR<NFMapEx<std::string, std::string>>(NF_NEW NFMapEx<std::string, std::string>());
                    }
                    else
                    {
                        mxEmbeddedMap->ClearAll();
                    }

                    mxEmbeddedMap->AddElement(strKey, NF_SHARE_PTR<std::string>(NF_NEW std::string(strValue)))
                }
            }

            bRet = true;
        }
    }

    return bRet;
}

const NF_SHARE_PTR<NFList<std::string>> NFCProperty::GetEmbeddedList() const
{
    return this->mxEmbeddedList;
}

const NF_SHARE_PTR<NFMapEx<std::string, std::string>> NFCProperty::GetEmbeddedMap() const
{
    return this->mxEmbeddedMap;
}
<|endoftext|>


<commit_before>// NearIntegers.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

int main(int argc, char* argv[])
{
	const double epsilon = 0.0000001;
	srand(static_cast<unsigned int>(time(NULL)));

	while (1)
	{
		ExpressionMaker e;

		// Hack
		if (std::find(e.opCodes.begin(), e.opCodes.end(), Op_sin) == e.opCodes.end())
		{
			continue;
		}

		//printf("TESTING: \n");
		//e.Dump();

		double ret = e.Run();
		double modResult = fmod(ret, 1);

		// printf("MODRESULT: %.32f, %d, %d\n", modResult, static_cast<int>(modResult), static_cast<int>(modResult) != modResult);

		if (fabs(fmod(ret, 1)) < epsilon && fabs(ret) > 1 && fabs(ret) < 10 && static_cast<int>(modResult) != modResult)
		{
			printf("Found result: %f\n", ret);
			e.Dump();
			printf("\n");
		}
	}

	return 0;
}

ExpressionMaker::ExpressionMaker()
{
	int stackDepth = 1;
	opCodes.push_back(Op_value);
	while (1)
	{
		OpCode op;
		if (opCodes.size() > MaxOpCodes)
		{
			break;
		}
		else
		{
			op = static_cast<OpCode>(rand() % Op_value);
		}

		for (int i = stackDepth; i < opCodeArgCount[op]; ++i)
		{
			opCodes.push_back(Op_value);
			stackDepth++;
		}
		opCodes.push_back(op);
		stackDepth -= opCodeArgCount[op] - 1;
	}
}

void ExpressionMaker::Dump()
{
	auto it = values.begin();
	for (OpCode op : opCodes)
	{
		if (op == Op_value && it != values.end())
		{
			printf("%f\n", *it++);
		}
		else
		{
			printf("%s\n", opCodeNames[op]);
		}
	}
	assert(it == values.end());
}

double ExpressionMaker::MakeValue()
{
	return rand() % 100;
}

double ExpressionMaker::Run()
{
	std::list<double> stack;

	for (OpCode op : opCodes)
	{
		std::vector<double> args;
		assert(stack.size() >= static_cast<size_t>(opCodeArgCount[op]));

		// Build the arguments list.
		for (int i = 0; i < opCodeArgCount[op]; ++i)
		{
			args.push_back(stack.back());
			stack.pop_back();
		}

		double val;
		switch (op)
		{
		case Op_value:
			val = MakeValue();
			values.push_back(val);
			stack.push_back(val);
			break;
		case Op_add:
			stack.push_back(args[0] + args[1]);
			break;
		case Op_mul:
			stack.push_back(args[0] * args[1]);
			break;
		case Op_div:
			stack.push_back(args[0] / args[1]);
			break;
		case Op_sin:
			stack.push_back(sin(args[0]));
			break;
		case Op_log:
			stack.push_back(log(args[0]));
			break;
		}
	}

	// TODO: we will insert unnecessary values sometimes, ignore this
	// assert(stack.size() == 1);
	return stack.back();
}

char *opCodeNames[] = {
#define OPCODE(name, numArgs) \
	#name
#include "OpCodes.h"
#undef OPCODE
};

int opCodeArgCount[] = {
#define OPCODE(name, numArgs) \
	numArgs
#include "OpCodes.h"
#undef OPCODE
};
<commit_msg>Add a MRU list<commit_after>// NearIntegers.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

int main(int argc, char* argv[])
{
	const double epsilon = 0.00000001;
	srand(static_cast<unsigned int>(time(NULL)));

	std::list<std::list<OpCode>> seen;

	while (1)
	{
		ExpressionMaker e;

		// Hack
		if (std::find(e.opCodes.begin(), e.opCodes.end(), Op_sin) == e.opCodes.end())
		{
			continue;
		}

		//printf("TESTING: \n");
		//e.Dump();

		double ret = e.Run();
		double modResult = fmod(ret, 1);

		// printf("MODRESULT: %.32f, %d, %d\n", modResult, static_cast<int>(modResult), static_cast<int>(modResult) != modResult);

		if (fabs(fmod(ret, 1)) < epsilon && fabs(ret) > 1 && fabs(ret) < 10 && static_cast<int>(modResult) != modResult)
		{
			// This is expensive, but should be rare.
			bool seenBefore = false;
			for (auto it = seen.begin(); it != seen.end(); ++it)
			{
				if (it->size() == e.opCodes.size())
				{
					for (auto x1 = it->begin(), x2 = e.opCodes.begin(); x1 != it->end(); ++x1, ++x2)
					{
						if (*x1 != *x2)
						{
							break;
						}
					}

					seenBefore = true;
					break;
				}
			}

			if (!seenBefore)
			{
				printf("Found result: %f\n", ret);
				e.Dump();
				printf("\n");
				seen.push_back(e.opCodes);
			}
		}
	}

	return 0;
}

ExpressionMaker::ExpressionMaker()
{
	int stackDepth = 1;
	opCodes.push_back(Op_value);
	while (1)
	{
		OpCode op;
		if (opCodes.size() > MaxOpCodes)
		{
			break;
		}
		else
		{
			op = static_cast<OpCode>(rand() % Op_value);
		}

		for (int i = stackDepth; i < opCodeArgCount[op]; ++i)
		{
			opCodes.push_back(Op_value);
			stackDepth++;
		}
		opCodes.push_back(op);
		stackDepth -= opCodeArgCount[op] - 1;
	}
}

void ExpressionMaker::Dump()
{
	auto it = values.begin();
	for (OpCode op : opCodes)
	{
		if (op == Op_value && it != values.end())
		{
			printf("%f\n", *it++);
		}
		else
		{
			printf("%s\n", opCodeNames[op]);
		}
	}
	assert(it == values.end());
}

double ExpressionMaker::MakeValue()
{
	return rand() % 100;
}

double ExpressionMaker::Run()
{
	std::list<double> stack;

	for (OpCode op : opCodes)
	{
		std::vector<double> args;
		assert(stack.size() >= static_cast<size_t>(opCodeArgCount[op]));

		// Build the arguments list.
		for (int i = 0; i < opCodeArgCount[op]; ++i)
		{
			args.push_back(stack.back());
			stack.pop_back();
		}

		double val;
		switch (op)
		{
		case Op_value:
			val = MakeValue();
			values.push_back(val);
			stack.push_back(val);
			break;
		case Op_add:
			stack.push_back(args[0] + args[1]);
			break;
		case Op_mul:
			stack.push_back(args[0] * args[1]);
			break;
		case Op_div:
			stack.push_back(args[0] / args[1]);
			break;
		case Op_sin:
			stack.push_back(sin(args[0]));
			break;
		case Op_log:
			stack.push_back(log(args[0]));
			break;
		}
	}

	// TODO: we will insert unnecessary values sometimes, ignore this
	// assert(stack.size() == 1);
	return stack.back();
}

char *opCodeNames[] = {
#define OPCODE(name, numArgs) \
	#name
#include "OpCodes.h"
#undef OPCODE
};

int opCodeArgCount[] = {
#define OPCODE(name, numArgs) \
	numArgs
#include "OpCodes.h"
#undef OPCODE
};
<|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkVerboseLimitedLinearUndo.h"
#include "mitkOperationEvent.h"

mitk::VerboseLimitedLinearUndo::VerboseLimitedLinearUndo()
{
}

mitk::VerboseLimitedLinearUndo::~VerboseLimitedLinearUndo()
{
}

bool mitk::VerboseLimitedLinearUndo::SetOperationEvent(UndoStackItem *undoStackItem)
{
  if (!undoStackItem)
    return false;

  // clear the redolist, if a new operation is saved
  if (!m_RedoList.empty())
  {
    this->ClearList(&m_RedoList);
    InvokeEvent(RedoEmptyEvent());
  }

  std::size_t undoLimit = this->GetUndoLimit();
  if (undoLimit > 0 && m_UndoList.size() == undoLimit)
  {
    m_UndoList.pop_front();
  }
  m_UndoList.push_back(undoStackItem);

  InvokeEvent(UndoNotEmptyEvent());

  return true;
}

mitk::VerboseLimitedLinearUndo::StackDescription mitk::VerboseLimitedLinearUndo::GetUndoDescriptions()
{
  mitk::VerboseLimitedLinearUndo::StackDescription descriptions;

  if (m_UndoList.empty())
    return descriptions;

  int oeid = m_UndoList.back()->GetObjectEventId(); // ObjectEventID of current group
  std::string currentDescription;                   // description of current group
  int currentDescriptionCount(0);                   // counter, how many items of the current group gave descriptions
  bool niceDescriptionFound(false);                 // have we yet seen a plain descriptive entry (not OperationEvent)?
  std::string lastDescription; // stores the last description to inhibit entries like "name AND name AND name..." if
                               // name is always the same

  for (auto iter = m_UndoList.rbegin(); iter != m_UndoList.rend(); ++iter)
  {
    if (oeid != (*iter)->GetObjectEventId())
    {
      // current description complete, append to list
      if (currentDescription.empty())
        currentDescription = "Some unnamed action"; // set a default description

      descriptions.push_back(StackDescriptionItem(oeid, currentDescription));

      currentDescription = ""; // prepare for next group
      currentDescriptionCount = 0;
      niceDescriptionFound = false;
      oeid = (*iter)->GetObjectEventId();
    }

    if (!(*iter)->GetDescription().empty()) // if there is a description
    {
      if (!dynamic_cast<OperationEvent *>(*iter))
      {
        // anything but an OperationEvent overrides the collected descriptions
        currentDescription = (*iter)->GetDescription();
        niceDescriptionFound = true;
      }
      else if (!niceDescriptionFound) // mere descriptive items override OperationEvents' descriptions
      {
        if (currentDescriptionCount) // if we have already seen another description
        {
          if (lastDescription != (*iter)->GetDescription())
          {
            // currentDescription += '\n';           // concatenate descriptions with newline
            currentDescription += " AND "; // this has to wait until the popup can process multiline items
            currentDescription += (*iter)->GetDescription();
          }
        }
        else
        {
          currentDescription += (*iter)->GetDescription();
        }
      }
      lastDescription = (*iter)->GetDescription();
      ++currentDescriptionCount;
    }

  } // for

  // add last description to list
  if (currentDescription.empty())
    currentDescription = "Some unnamed action";
  descriptions.push_back(StackDescriptionItem(oeid, currentDescription));

  return descriptions; // list ready
}

mitk::VerboseLimitedLinearUndo::StackDescription mitk::VerboseLimitedLinearUndo::GetRedoDescriptions()
{
  mitk::VerboseLimitedLinearUndo::StackDescription descriptions;

  if (m_RedoList.empty())
    return descriptions;

  int oeid = m_RedoList.back()->GetObjectEventId(); // ObjectEventID of current group
  std::string currentDescription;                   // description of current group
  int currentDescriptionCount(0);                   // counter, how many items of the current group gave descriptions
  bool niceDescriptionFound(false);                 // have we yet seen a plain descriptive entry (not OperationEvent)?
  std::string lastDescription; // stores the last description to inhibit entries like "name AND name AND name..." if
                               // name is always the same

  for (auto iter = m_RedoList.rbegin(); iter != m_RedoList.rend(); ++iter)
  {
    if (oeid != (*iter)->GetObjectEventId())
    {
      // current description complete, append to list
      if (currentDescription.empty())
        currentDescription = "Some unnamed action"; // set a default description

      descriptions.push_back(StackDescriptionItem(oeid, currentDescription));

      currentDescription = ""; // prepare for next group
      currentDescriptionCount = 0;
      niceDescriptionFound = false;
      oeid = (*iter)->GetObjectEventId();
    }

    if (!(*iter)->GetDescription().empty()) // if there is a description
    {
      if (!dynamic_cast<OperationEvent *>(*iter))
      {
        // anything but an OperationEvent overrides the collected descriptions
        currentDescription = (*iter)->GetDescription();
        niceDescriptionFound = true;
      }
      else if (!niceDescriptionFound) // mere descriptive items override OperationEvents' descriptions
      {
        if (currentDescriptionCount) // if we have already seen another description
        {
          if (lastDescription != (*iter)->GetDescription())
          {
            // currentDescription += '\n';           // concatenate descriptions with newline
            currentDescription += " AND "; // this has to wait until the popup can process multiline items
            currentDescription += (*iter)->GetDescription();
          }
        }
        else
        {
          currentDescription += (*iter)->GetDescription();
        }
      }
      lastDescription = (*iter)->GetDescription();
      ++currentDescriptionCount;
    }

  } // for

  // add last description to list
  if (currentDescription.empty())
    currentDescription = "Some unnamed action";
  descriptions.push_back(StackDescriptionItem(oeid, currentDescription));

  return descriptions; // list ready
}
<commit_msg>Fix memory leak<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkVerboseLimitedLinearUndo.h"
#include "mitkOperationEvent.h"

mitk::VerboseLimitedLinearUndo::VerboseLimitedLinearUndo()
{
}

mitk::VerboseLimitedLinearUndo::~VerboseLimitedLinearUndo()
{
}

bool mitk::VerboseLimitedLinearUndo::SetOperationEvent(UndoStackItem *undoStackItem)
{
  if (!undoStackItem)
    return false;

  // clear the redolist, if a new operation is saved
  if (!m_RedoList.empty())
  {
    this->ClearList(&m_RedoList);
    InvokeEvent(RedoEmptyEvent());
  }

  std::size_t undoLimit = this->GetUndoLimit();
  if (0 != undoLimit && m_UndoList.size() == undoLimit)
  {
    auto item = m_UndoList.front();
    m_UndoList.pop_front();
    delete item;
  }
  m_UndoList.push_back(undoStackItem);

  InvokeEvent(UndoNotEmptyEvent());

  return true;
}

mitk::VerboseLimitedLinearUndo::StackDescription mitk::VerboseLimitedLinearUndo::GetUndoDescriptions()
{
  mitk::VerboseLimitedLinearUndo::StackDescription descriptions;

  if (m_UndoList.empty())
    return descriptions;

  int oeid = m_UndoList.back()->GetObjectEventId(); // ObjectEventID of current group
  std::string currentDescription;                   // description of current group
  int currentDescriptionCount(0);                   // counter, how many items of the current group gave descriptions
  bool niceDescriptionFound(false);                 // have we yet seen a plain descriptive entry (not OperationEvent)?
  std::string lastDescription; // stores the last description to inhibit entries like "name AND name AND name..." if
                               // name is always the same

  for (auto iter = m_UndoList.rbegin(); iter != m_UndoList.rend(); ++iter)
  {
    if (oeid != (*iter)->GetObjectEventId())
    {
      // current description complete, append to list
      if (currentDescription.empty())
        currentDescription = "Some unnamed action"; // set a default description

      descriptions.push_back(StackDescriptionItem(oeid, currentDescription));

      currentDescription = ""; // prepare for next group
      currentDescriptionCount = 0;
      niceDescriptionFound = false;
      oeid = (*iter)->GetObjectEventId();
    }

    if (!(*iter)->GetDescription().empty()) // if there is a description
    {
      if (!dynamic_cast<OperationEvent *>(*iter))
      {
        // anything but an OperationEvent overrides the collected descriptions
        currentDescription = (*iter)->GetDescription();
        niceDescriptionFound = true;
      }
      else if (!niceDescriptionFound) // mere descriptive items override OperationEvents' descriptions
      {
        if (currentDescriptionCount) // if we have already seen another description
        {
          if (lastDescription != (*iter)->GetDescription())
          {
            // currentDescription += '\n';           // concatenate descriptions with newline
            currentDescription += " AND "; // this has to wait until the popup can process multiline items
            currentDescription += (*iter)->GetDescription();
          }
        }
        else
        {
          currentDescription += (*iter)->GetDescription();
        }
      }
      lastDescription = (*iter)->GetDescription();
      ++currentDescriptionCount;
    }

  } // for

  // add last description to list
  if (currentDescription.empty())
    currentDescription = "Some unnamed action";
  descriptions.push_back(StackDescriptionItem(oeid, currentDescription));

  return descriptions; // list ready
}

mitk::VerboseLimitedLinearUndo::StackDescription mitk::VerboseLimitedLinearUndo::GetRedoDescriptions()
{
  mitk::VerboseLimitedLinearUndo::StackDescription descriptions;

  if (m_RedoList.empty())
    return descriptions;

  int oeid = m_RedoList.back()->GetObjectEventId(); // ObjectEventID of current group
  std::string currentDescription;                   // description of current group
  int currentDescriptionCount(0);                   // counter, how many items of the current group gave descriptions
  bool niceDescriptionFound(false);                 // have we yet seen a plain descriptive entry (not OperationEvent)?
  std::string lastDescription; // stores the last description to inhibit entries like "name AND name AND name..." if
                               // name is always the same

  for (auto iter = m_RedoList.rbegin(); iter != m_RedoList.rend(); ++iter)
  {
    if (oeid != (*iter)->GetObjectEventId())
    {
      // current description complete, append to list
      if (currentDescription.empty())
        currentDescription = "Some unnamed action"; // set a default description

      descriptions.push_back(StackDescriptionItem(oeid, currentDescription));

      currentDescription = ""; // prepare for next group
      currentDescriptionCount = 0;
      niceDescriptionFound = false;
      oeid = (*iter)->GetObjectEventId();
    }

    if (!(*iter)->GetDescription().empty()) // if there is a description
    {
      if (!dynamic_cast<OperationEvent *>(*iter))
      {
        // anything but an OperationEvent overrides the collected descriptions
        currentDescription = (*iter)->GetDescription();
        niceDescriptionFound = true;
      }
      else if (!niceDescriptionFound) // mere descriptive items override OperationEvents' descriptions
      {
        if (currentDescriptionCount) // if we have already seen another description
        {
          if (lastDescription != (*iter)->GetDescription())
          {
            // currentDescription += '\n';           // concatenate descriptions with newline
            currentDescription += " AND "; // this has to wait until the popup can process multiline items
            currentDescription += (*iter)->GetDescription();
          }
        }
        else
        {
          currentDescription += (*iter)->GetDescription();
        }
      }
      lastDescription = (*iter)->GetDescription();
      ++currentDescriptionCount;
    }

  } // for

  // add last description to list
  if (currentDescription.empty())
    currentDescription = "Some unnamed action";
  descriptions.push_back(StackDescriptionItem(oeid, currentDescription));

  return descriptions; // list ready
}
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkGenericAttributeCollection.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
// .NAME vtkGenericAttributeCollection - objects that own attributes of a data set
// .DESCRIPTION They can also select an active attribute component to process
// (contouring, clipping) and others attributes to interpolate.

#include "vtkGenericAttributeCollection.h"

#include "vtkObjectFactory.h"
#include "vtkGenericAttribute.h"

#include <vtkstd/vector>
#include <assert.h>

vtkCxxRevisionMacro(vtkGenericAttributeCollection,"1.1");
vtkStandardNewMacro(vtkGenericAttributeCollection);

class vtkGenericAttributeInternalVector
{
public:
  typedef vtkstd::vector<vtkGenericAttribute* > VectorType;
  VectorType Vector;
};

//----------------------------------------------------------------------------
// Description:
// Default constructor: empty collection
vtkGenericAttributeCollection::vtkGenericAttributeCollection()
{
  this->AttributeInternalVector = new vtkGenericAttributeInternalVector;
  this->ActiveAttribute = 0;
  this->ActiveComponent = 0;
  this->NumberOfAttributesToInterpolate = 0;
  this->NumberOfComponents = 0;
  this->MaxNumberOfComponents = 0; // cache
  this->ActualMemorySize = 0;
}

//----------------------------------------------------------------------------
vtkGenericAttributeCollection::~vtkGenericAttributeCollection()
{
  for(unsigned int i = 0; i < this->AttributeInternalVector->Vector.size(); ++i)
    {
    this->AttributeInternalVector->Vector[i]->Delete();
    }
  delete this->AttributeInternalVector;
}

//----------------------------------------------------------------------------
void vtkGenericAttributeCollection::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  int i;
  int c = this->GetNumberOfAttributes();

  os << indent << "Number Of Attributes: " << this->GetNumberOfAttributes() << "\n";
  for(i=0; i<c; ++i)
    {
    os << indent << "Attribute #"<<i<<":\n";
    this->GetAttribute(i)->PrintSelf(os,indent.GetNextIndent());
    }

  c=this->GetNumberOfAttributesToInterpolate();
  os << indent << "Number Of Attributes to interpolate: " << c << endl;

  os << indent << "Attributes to interpolate:";

  for(i=0; i<c; ++i)
    {
    os << ' ' << this->AttributesToInterpolate[i];
    }
  os << endl;

  os << indent << "Active Attribute: " << this->ActiveAttribute << endl;

  os << indent << "Active Component" << this->ActiveComponent << endl;
}

//----------------------------------------------------------------------------
// Description:
// Number of attributes.
int vtkGenericAttributeCollection::GetNumberOfAttributes()
{
  int result = this->AttributeInternalVector->Vector.size();
  //assert("post: positive_result" && result>=0); size() is an unsigned type according to STL vector definition
  return result;
}

//----------------------------------------------------------------------------
int vtkGenericAttributeCollection::GetNumberOfComponents()
{
  this->ComputeNumbers();

  return this->NumberOfComponents;
}

//----------------------------------------------------------------------------
// Description:
// Maximum number of components encountered among all attributes.
// \post positive_result: result>=0
// \post valid_result: result<=GetNumberOfComponents()
int vtkGenericAttributeCollection::GetMaxNumberOfComponents()
{
  this->ComputeNumbers();

  assert("post: positive_result" && this->MaxNumberOfComponents>=0);
  assert("post: valid_result" && this->MaxNumberOfComponents<=GetNumberOfComponents());
  return this->MaxNumberOfComponents;
}

//----------------------------------------------------------------------------
// Description:
// Actual size of the data in kilobytes; only valid after the pipeline has
// updated. It is guaranteed to be greater than or equal to the memory
// required to represent the data.
unsigned long vtkGenericAttributeCollection::GetActualMemorySize()
{
  this->ComputeNumbers();
  return this->ActualMemorySize;
}

//----------------------------------------------------------------------------
// Description:
// Does `this' have no attribute?
int vtkGenericAttributeCollection::IsEmpty()
{
  return this->GetNumberOfAttributes()==0;
}

//----------------------------------------------------------------------------
// Description:
// Attribute `i'.
vtkGenericAttribute *vtkGenericAttributeCollection::GetAttribute(int i)
{
  assert("pre: not_empty" && !IsEmpty());
  assert("pre: valid_i" && (i>=0)&&(i<this->GetNumberOfAttributes()));
  vtkGenericAttribute *result=this->AttributeInternalVector->Vector[i];
  assert("post: result_exists" && result!=0);
  return result;
}

//----------------------------------------------------------------------------
// Description:
// Return the index of attribute `name', if found. Return -1 otherwise.
int vtkGenericAttributeCollection::FindAttribute(const char *name)
{
  assert("pre: name_exists:" && name!=0);

  int numAtt = this->GetNumberOfAttributes();
  for( int i = 0; i < numAtt; ++i )
    {
    if( strcmp( this->GetAttribute(i)->GetName(), name ) == 0)
      {
      return i;
      }
    }

  return -1;
}

//----------------------------------------------------------------------------
// Description:
// Add attribute `a' at the end.
void vtkGenericAttributeCollection::InsertNextAttribute(vtkGenericAttribute *a)
{
  assert("pre: a_exists" && a!=0);
#ifndef NDEBUG
  int oldnumber=this->GetNumberOfAttributes();
#endif

  this->AttributeInternalVector->Vector.push_back(a);
  this->Modified();

  assert("post: more_items" && this->GetNumberOfAttributes()==oldnumber+1);
  assert("post: a_is_set" && this->GetAttribute(this->GetNumberOfAttributes()-1)==a);
}

//----------------------------------------------------------------------------
// Description:
// Replace attribute at index `i' by `a'.
void vtkGenericAttributeCollection::InsertAttribute(int i, vtkGenericAttribute *a)
{
  assert("pre: not_empty" && !this->IsEmpty());
  assert("pre: a_exists" && a!=0);
  assert("pre: valid_i" && (i>=0)&&(i<this->GetNumberOfAttributes()));

#ifndef NDEBUG
int oldnumber = this->GetNumberOfAttributes();
#endif

  this->AttributeInternalVector->Vector[i] = a;
  this->Modified();

  assert("post: more_items" && this->GetNumberOfAttributes()==oldnumber);
  assert("post: a_is_set" && this->GetAttribute(i)==a);
}

//----------------------------------------------------------------------------
// Description:
// Remove Attribute at `i'.
void vtkGenericAttributeCollection::RemoveAttribute(int i)
{
  assert("pre: not_empty" && !this->IsEmpty());
  assert("pre: valid_i" && (i>=0)&&(i<this->GetNumberOfAttributes()));

#ifndef NDEBUG
  int oldnumber=this->GetNumberOfAttributes();
#endif

  this->AttributeInternalVector->Vector.erase(
    this->AttributeInternalVector->Vector.begin()+i);
  this->Modified();

  assert("post: fewer_items" && this->GetNumberOfAttributes()==(oldnumber-1));
}

//----------------------------------------------------------------------------
// Description:
// Remove all attributes.
void vtkGenericAttributeCollection::Reset()
{
  for(unsigned int i = 0; i < this->AttributeInternalVector->Vector.size(); ++i)
    {
    this->AttributeInternalVector->Vector[i]->Delete();
    }
  this->AttributeInternalVector->Vector.clear();
  this->Modified();

  assert("post: is_empty" && this->IsEmpty());
}

//----------------------------------------------------------------------------
// Description:
// Recursive duplication of `other' in `this'.
void vtkGenericAttributeCollection::DeepCopy(vtkGenericAttributeCollection *other)
{
  assert("pre: other_exists" && other!=0);
  assert("pre: not_self" && other!=this);

  this->AttributeInternalVector->Vector.resize(
    other->AttributeInternalVector->Vector.size());

  int c = this->AttributeInternalVector->Vector.size();
  for(int i=0; i<c; i++)
    {
    if(this->AttributeInternalVector->Vector[i] == 0)
      {
      this->AttributeInternalVector->Vector[i] =
        other->AttributeInternalVector->Vector[i]->NewInstance();
      }
    this->AttributeInternalVector->Vector[i]->DeepCopy(
      other->AttributeInternalVector->Vector[i]);
    }
  this->Modified();

  assert("post: same_size" && this->GetNumberOfAttributes()==other->GetNumberOfAttributes());
}

//----------------------------------------------------------------------------
// Description:
// Update `this' using fields of `other'.
void vtkGenericAttributeCollection::ShallowCopy(vtkGenericAttributeCollection *other)
{
  assert("pre: other_exists" && other!=0);
  assert("pre: not_self" && other!=this);

  this->AttributeInternalVector->Vector =
    other->AttributeInternalVector->Vector;
  this->Modified();

  assert("post: same_size" && this->GetNumberOfAttributes()==other->GetNumberOfAttributes());
}

//----------------------------------------------------------------------------
// Description:
// Collection is composite object and need to check each part for MTime.
unsigned long int vtkGenericAttributeCollection::GetMTime()
{
  unsigned long result;
  unsigned long mtime;

  result = vtkObject::GetMTime();

  for(int i = 0; i < this->GetNumberOfAttributes(); ++i)
    {
    mtime = this->GetAttribute(i)->GetMTime();
    result = ( mtime > result ? mtime : result );
    }

  return result;
}

//----------------------------------------------------------------------------
// Description:
// Compute number of components, max number of components and actual memory
// size.
void vtkGenericAttributeCollection::ComputeNumbers()
{
  if ( this->GetMTime() > this->ComputeTime )
    {
    int nb = 0;
    int count = 0;
    int maxNb = 0;
    unsigned long memory=0;

    int c = this->GetNumberOfAttributes();

    for(int i = 0; i < c; ++i)
      {
      count = this->GetAttribute(i)->GetNumberOfComponents();
      memory=memory+this->GetAttribute(i)->GetActualMemorySize();
      if(count > maxNb)
        {
        maxNb = count;
        }
      nb += count;
      }

    this->NumberOfComponents = nb;
    this->MaxNumberOfComponents = maxNb;
    this->ActualMemorySize = memory;

    assert("check: positive_number" && this->NumberOfComponents>=0);
    assert("check: positiveMaxNumber" && this->MaxNumberOfComponents>=0);
    assert("check: valid_number" && this->MaxNumberOfComponents<=this->NumberOfComponents);
    this->ComputeTime.Modified();
    }
}

//----------------------------------------------------------------------------
// *** ALL THE FOLLOWING METHODS SHOULD BE REMOVED WHEN vtkInformation
// will be ready.
// *** BEGIN

// Description:
// Set the scalar attribute to be processed.
void vtkGenericAttributeCollection::SetActiveAttribute(int attribute,
                                                       int component)
{
  assert("pre: not_empty" && !IsEmpty());
  assert("pre: valid_attribute" && (attribute>=0)&&(attribute<this->GetNumberOfAttributes()));
  assert("pre: valid_component" && (component>=0)&&(component<this->GetAttribute(attribute)->GetNumberOfComponents()));

  this->ActiveAttribute = attribute;
  this->ActiveComponent = component;

  assert("post: is_set" && (this->GetActiveAttribute()==attribute) && (this->GetActiveComponent()==component));
}

//----------------------------------------------------------------------------
// Description:
// Indices of attributes to interpolate.
// \pre not_empty: !IsEmpty()
// \post valid_result: GetNumberOfAttributesToInterpolate()>0 implies
//                       result!=0
int *vtkGenericAttributeCollection::GetAttributesToInterpolate()
{
  assert("pre: not_empty" && !IsEmpty());

  assert("post: valid_result" && ((!(this->NumberOfAttributesToInterpolate>0))
                                  || this->AttributesToInterpolate!=0));
  // A=>B !A||B

  return this->AttributesToInterpolate;
}

//----------------------------------------------------------------------------
// Description
// Does the array `attributes' of size `size' have `attribute'?
int vtkGenericAttributeCollection::HasAttribute(int size,
                                                int *attributes,
                                                int attribute)
{
  assert("pre: positive_size" && size>=0);
  assert("pre: valid_attributes" && ((!(size>0))||(attributes!=0))); // size>0 => attributes!=0 (A=>B: !A||B )

  int result = 0; // false
  int i;

  if(size != 0)
    {
    i = 0;
    while( !result && i++ < size )
      {
      result = attributes[i] == attribute;
      }
    }
  return result;
}

//----------------------------------------------------------------------------
// Description:
// Set the attributes to interpolate.
void vtkGenericAttributeCollection::SetAttributesToInterpolate(int size,
                                                               int *attributes)
{
  assert("pre: not_empty" && !this->IsEmpty());
  assert("pre: positive_size" && size>=0);
  assert("pre: magic_number" && size<=10);
  assert("pre: valid_attributes" && ((!(size>0))||(attributes!=0)));  // size>0 => attributes!=0 (A=>B: !A||B )
  assert("pre: valid_attributes_contents" && (!(attributes!=0) || !(!this->HasAttribute(size,attributes,this->GetActiveAttribute())))); // attributes!=0 => !this->HasAttribute(size,attributes,this->GetActiveAttribute()) (A=>B: !A||B )

  this->NumberOfAttributesToInterpolate = size;
  for(int i=0; i<size; ++i)
    {
    this->AttributesToInterpolate[i] = attributes[i];
    }

  assert("post: is_set" && (this->GetNumberOfAttributesToInterpolate()==size));
}

//----------------------------------------------------------------------------
// Description:
// Set the attributes to interpolate.
void vtkGenericAttributeCollection::SetAttributesToInterpolateToAll()
{
  assert("pre: not_empty" && !this->IsEmpty());

  this->NumberOfAttributesToInterpolate = this->GetMaxNumberOfComponents();
  for(int i=0; i<this->NumberOfAttributesToInterpolate; ++i)
    {
    this->AttributesToInterpolate[i] = i;
    }
}

//----------------------------------------------------------------------------
// *** ALL THE PREVIOUS METHODS SHOULD BE REMOVED WHEN vtkInformation
// will be ready.
// *** END
<commit_msg>DOC: doxygen in cxx are not seen<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkGenericAttributeCollection.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

#include "vtkGenericAttributeCollection.h"

#include "vtkObjectFactory.h"
#include "vtkGenericAttribute.h"

#include <vtkstd/vector>
#include <assert.h>

vtkCxxRevisionMacro(vtkGenericAttributeCollection,"1.2");
vtkStandardNewMacro(vtkGenericAttributeCollection);

class vtkGenericAttributeInternalVector
{
public:
  typedef vtkstd::vector<vtkGenericAttribute* > VectorType;
  VectorType Vector;
};

//----------------------------------------------------------------------------
// Description:
// Default constructor: empty collection
vtkGenericAttributeCollection::vtkGenericAttributeCollection()
{
  this->AttributeInternalVector = new vtkGenericAttributeInternalVector;
  this->ActiveAttribute = 0;
  this->ActiveComponent = 0;
  this->NumberOfAttributesToInterpolate = 0;
  this->NumberOfComponents = 0;
  this->MaxNumberOfComponents = 0; // cache
  this->ActualMemorySize = 0;
}

//----------------------------------------------------------------------------
vtkGenericAttributeCollection::~vtkGenericAttributeCollection()
{
  for(unsigned int i = 0; i < this->AttributeInternalVector->Vector.size(); ++i)
    {
    this->AttributeInternalVector->Vector[i]->Delete();
    }
  delete this->AttributeInternalVector;
}

//----------------------------------------------------------------------------
void vtkGenericAttributeCollection::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  int i;
  int c = this->GetNumberOfAttributes();

  os << indent << "Number Of Attributes: " << this->GetNumberOfAttributes() << "\n";
  for(i=0; i<c; ++i)
    {
    os << indent << "Attribute #"<<i<<":\n";
    this->GetAttribute(i)->PrintSelf(os,indent.GetNextIndent());
    }

  c=this->GetNumberOfAttributesToInterpolate();
  os << indent << "Number Of Attributes to interpolate: " << c << endl;

  os << indent << "Attributes to interpolate:";

  for(i=0; i<c; ++i)
    {
    os << ' ' << this->AttributesToInterpolate[i];
    }
  os << endl;

  os << indent << "Active Attribute: " << this->ActiveAttribute << endl;

  os << indent << "Active Component" << this->ActiveComponent << endl;
}

//----------------------------------------------------------------------------
// Description:
// Number of attributes.
int vtkGenericAttributeCollection::GetNumberOfAttributes()
{
  int result = this->AttributeInternalVector->Vector.size();
  //assert("post: positive_result" && result>=0); size() is an unsigned type according to STL vector definition
  return result;
}

//----------------------------------------------------------------------------
int vtkGenericAttributeCollection::GetNumberOfComponents()
{
  this->ComputeNumbers();

  return this->NumberOfComponents;
}

//----------------------------------------------------------------------------
// Description:
// Maximum number of components encountered among all attributes.
// \post positive_result: result>=0
// \post valid_result: result<=GetNumberOfComponents()
int vtkGenericAttributeCollection::GetMaxNumberOfComponents()
{
  this->ComputeNumbers();

  assert("post: positive_result" && this->MaxNumberOfComponents>=0);
  assert("post: valid_result" && this->MaxNumberOfComponents<=GetNumberOfComponents());
  return this->MaxNumberOfComponents;
}

//----------------------------------------------------------------------------
// Description:
// Actual size of the data in kilobytes; only valid after the pipeline has
// updated. It is guaranteed to be greater than or equal to the memory
// required to represent the data.
unsigned long vtkGenericAttributeCollection::GetActualMemorySize()
{
  this->ComputeNumbers();
  return this->ActualMemorySize;
}

//----------------------------------------------------------------------------
// Description:
// Does `this' have no attribute?
int vtkGenericAttributeCollection::IsEmpty()
{
  return this->GetNumberOfAttributes()==0;
}

//----------------------------------------------------------------------------
// Description:
// Attribute `i'.
vtkGenericAttribute *vtkGenericAttributeCollection::GetAttribute(int i)
{
  assert("pre: not_empty" && !IsEmpty());
  assert("pre: valid_i" && (i>=0)&&(i<this->GetNumberOfAttributes()));
  vtkGenericAttribute *result=this->AttributeInternalVector->Vector[i];
  assert("post: result_exists" && result!=0);
  return result;
}

//----------------------------------------------------------------------------
// Description:
// Return the index of attribute `name', if found. Return -1 otherwise.
int vtkGenericAttributeCollection::FindAttribute(const char *name)
{
  assert("pre: name_exists:" && name!=0);

  int numAtt = this->GetNumberOfAttributes();
  for( int i = 0; i < numAtt; ++i )
    {
    if( strcmp( this->GetAttribute(i)->GetName(), name ) == 0)
      {
      return i;
      }
    }

  return -1;
}

//----------------------------------------------------------------------------
// Description:
// Add attribute `a' at the end.
void vtkGenericAttributeCollection::InsertNextAttribute(vtkGenericAttribute *a)
{
  assert("pre: a_exists" && a!=0);
#ifndef NDEBUG
  int oldnumber=this->GetNumberOfAttributes();
#endif

  this->AttributeInternalVector->Vector.push_back(a);
  this->Modified();

  assert("post: more_items" && this->GetNumberOfAttributes()==oldnumber+1);
  assert("post: a_is_set" && this->GetAttribute(this->GetNumberOfAttributes()-1)==a);
}

//----------------------------------------------------------------------------
// Description:
// Replace attribute at index `i' by `a'.
void vtkGenericAttributeCollection::InsertAttribute(int i, vtkGenericAttribute *a)
{
  assert("pre: not_empty" && !this->IsEmpty());
  assert("pre: a_exists" && a!=0);
  assert("pre: valid_i" && (i>=0)&&(i<this->GetNumberOfAttributes()));

#ifndef NDEBUG
int oldnumber = this->GetNumberOfAttributes();
#endif

  this->AttributeInternalVector->Vector[i] = a;
  this->Modified();

  assert("post: more_items" && this->GetNumberOfAttributes()==oldnumber);
  assert("post: a_is_set" && this->GetAttribute(i)==a);
}

//----------------------------------------------------------------------------
// Description:
// Remove Attribute at `i'.
void vtkGenericAttributeCollection::RemoveAttribute(int i)
{
  assert("pre: not_empty" && !this->IsEmpty());
  assert("pre: valid_i" && (i>=0)&&(i<this->GetNumberOfAttributes()));

#ifndef NDEBUG
  int oldnumber=this->GetNumberOfAttributes();
#endif

  this->AttributeInternalVector->Vector.erase(
    this->AttributeInternalVector->Vector.begin()+i);
  this->Modified();

  assert("post: fewer_items" && this->GetNumberOfAttributes()==(oldnumber-1));
}

//----------------------------------------------------------------------------
// Description:
// Remove all attributes.
void vtkGenericAttributeCollection::Reset()
{
  for(unsigned int i = 0; i < this->AttributeInternalVector->Vector.size(); ++i)
    {
    this->AttributeInternalVector->Vector[i]->Delete();
    }
  this->AttributeInternalVector->Vector.clear();
  this->Modified();

  assert("post: is_empty" && this->IsEmpty());
}

//----------------------------------------------------------------------------
// Description:
// Recursive duplication of `other' in `this'.
void vtkGenericAttributeCollection::DeepCopy(vtkGenericAttributeCollection *other)
{
  assert("pre: other_exists" && other!=0);
  assert("pre: not_self" && other!=this);

  this->AttributeInternalVector->Vector.resize(
    other->AttributeInternalVector->Vector.size());

  int c = this->AttributeInternalVector->Vector.size();
  for(int i=0; i<c; i++)
    {
    if(this->AttributeInternalVector->Vector[i] == 0)
      {
      this->AttributeInternalVector->Vector[i] =
        other->AttributeInternalVector->Vector[i]->NewInstance();
      }
    this->AttributeInternalVector->Vector[i]->DeepCopy(
      other->AttributeInternalVector->Vector[i]);
    }
  this->Modified();

  assert("post: same_size" && this->GetNumberOfAttributes()==other->GetNumberOfAttributes());
}

//----------------------------------------------------------------------------
// Description:
// Update `this' using fields of `other'.
void vtkGenericAttributeCollection::ShallowCopy(vtkGenericAttributeCollection *other)
{
  assert("pre: other_exists" && other!=0);
  assert("pre: not_self" && other!=this);

  this->AttributeInternalVector->Vector =
    other->AttributeInternalVector->Vector;
  this->Modified();

  assert("post: same_size" && this->GetNumberOfAttributes()==other->GetNumberOfAttributes());
}

//----------------------------------------------------------------------------
// Description:
// Collection is composite object and need to check each part for MTime.
unsigned long int vtkGenericAttributeCollection::GetMTime()
{
  unsigned long result;
  unsigned long mtime;

  result = vtkObject::GetMTime();

  for(int i = 0; i < this->GetNumberOfAttributes(); ++i)
    {
    mtime = this->GetAttribute(i)->GetMTime();
    result = ( mtime > result ? mtime : result );
    }

  return result;
}

//----------------------------------------------------------------------------
// Description:
// Compute number of components, max number of components and actual memory
// size.
void vtkGenericAttributeCollection::ComputeNumbers()
{
  if ( this->GetMTime() > this->ComputeTime )
    {
    int nb = 0;
    int count = 0;
    int maxNb = 0;
    unsigned long memory=0;

    int c = this->GetNumberOfAttributes();

    for(int i = 0; i < c; ++i)
      {
      count = this->GetAttribute(i)->GetNumberOfComponents();
      memory=memory+this->GetAttribute(i)->GetActualMemorySize();
      if(count > maxNb)
        {
        maxNb = count;
        }
      nb += count;
      }

    this->NumberOfComponents = nb;
    this->MaxNumberOfComponents = maxNb;
    this->ActualMemorySize = memory;

    assert("check: positive_number" && this->NumberOfComponents>=0);
    assert("check: positiveMaxNumber" && this->MaxNumberOfComponents>=0);
    assert("check: valid_number" && this->MaxNumberOfComponents<=this->NumberOfComponents);
    this->ComputeTime.Modified();
    }
}

//----------------------------------------------------------------------------
// *** ALL THE FOLLOWING METHODS SHOULD BE REMOVED WHEN vtkInformation
// will be ready.
// *** BEGIN

// Description:
// Set the scalar attribute to be processed.
void vtkGenericAttributeCollection::SetActiveAttribute(int attribute,
                                                       int component)
{
  assert("pre: not_empty" && !IsEmpty());
  assert("pre: valid_attribute" && (attribute>=0)&&(attribute<this->GetNumberOfAttributes()));
  assert("pre: valid_component" && (component>=0)&&(component<this->GetAttribute(attribute)->GetNumberOfComponents()));

  this->ActiveAttribute = attribute;
  this->ActiveComponent = component;

  assert("post: is_set" && (this->GetActiveAttribute()==attribute) && (this->GetActiveComponent()==component));
}

//----------------------------------------------------------------------------
// Description:
// Indices of attributes to interpolate.
// \pre not_empty: !IsEmpty()
// \post valid_result: GetNumberOfAttributesToInterpolate()>0 implies
//                       result!=0
int *vtkGenericAttributeCollection::GetAttributesToInterpolate()
{
  assert("pre: not_empty" && !IsEmpty());

  assert("post: valid_result" && ((!(this->NumberOfAttributesToInterpolate>0))
                                  || this->AttributesToInterpolate!=0));
  // A=>B !A||B

  return this->AttributesToInterpolate;
}

//----------------------------------------------------------------------------
// Description
// Does the array `attributes' of size `size' have `attribute'?
int vtkGenericAttributeCollection::HasAttribute(int size,
                                                int *attributes,
                                                int attribute)
{
  assert("pre: positive_size" && size>=0);
  assert("pre: valid_attributes" && ((!(size>0))||(attributes!=0))); // size>0 => attributes!=0 (A=>B: !A||B )

  int result = 0; // false
  int i;

  if(size != 0)
    {
    i = 0;
    while( !result && i++ < size )
      {
      result = attributes[i] == attribute;
      }
    }
  return result;
}

//----------------------------------------------------------------------------
// Description:
// Set the attributes to interpolate.
void vtkGenericAttributeCollection::SetAttributesToInterpolate(int size,
                                                               int *attributes)
{
  assert("pre: not_empty" && !this->IsEmpty());
  assert("pre: positive_size" && size>=0);
  assert("pre: magic_number" && size<=10);
  assert("pre: valid_attributes" && ((!(size>0))||(attributes!=0)));  // size>0 => attributes!=0 (A=>B: !A||B )
  assert("pre: valid_attributes_contents" && (!(attributes!=0) || !(!this->HasAttribute(size,attributes,this->GetActiveAttribute())))); // attributes!=0 => !this->HasAttribute(size,attributes,this->GetActiveAttribute()) (A=>B: !A||B )

  this->NumberOfAttributesToInterpolate = size;
  for(int i=0; i<size; ++i)
    {
    this->AttributesToInterpolate[i] = attributes[i];
    }

  assert("post: is_set" && (this->GetNumberOfAttributesToInterpolate()==size));
}

//----------------------------------------------------------------------------
// Description:
// Set the attributes to interpolate.
void vtkGenericAttributeCollection::SetAttributesToInterpolateToAll()
{
  assert("pre: not_empty" && !this->IsEmpty());

  this->NumberOfAttributesToInterpolate = this->GetMaxNumberOfComponents();
  for(int i=0; i<this->NumberOfAttributesToInterpolate; ++i)
    {
    this->AttributesToInterpolate[i] = i;
    }
}

//----------------------------------------------------------------------------
// *** ALL THE PREVIOUS METHODS SHOULD BE REMOVED WHEN vtkInformation
// will be ready.
// *** END
<|endoftext|>


<commit_before>/* License: Apache 2.0. See LICENSE file in root directory.
Copyright(c) 2017 Intel Corporation. All Rights Reserved. */

#include "python.hpp"
#include "../include/librealsense2/hpp/rs_sensor.hpp"
#include "calibrated-sensor.h"

void init_sensor(py::module &m) {
    /** rs_sensor.hpp **/
    py::class_<rs2::notification> notification(m, "notification"); // No docstring in C++
    notification.def(py::init<>())
        .def("get_category", &rs2::notification::get_category,
             "Retrieve the notification's category.")
        .def_property_readonly("category", &rs2::notification::get_category,
             "The notification's category. Identical to calling get_category.")
        .def("get_description", &rs2::notification::get_description,
             "Retrieve the notification's description.")
        .def_property_readonly("description", &rs2::notification::get_description,
             "The notification's description. Identical to calling get_description.")
        .def("get_timestamp", &rs2::notification::get_timestamp,
             "Retrieve the notification's arrival timestamp.")
        .def_property_readonly("timestamp", &rs2::notification::get_timestamp,
             "The notification's arrival timestamp. Identical to calling get_timestamp.")
        .def("get_severity", &rs2::notification::get_severity,
             "Retrieve the notification's severity.")
        .def_property_readonly("severity", &rs2::notification::get_severity,
             "The notification's severity. Identical to calling get_severity.")
        .def("get_serialized_data", &rs2::notification::get_severity,
             "Retrieve the notification's serialized data.")
        .def_property_readonly("serialized_data", &rs2::notification::get_serialized_data,
             "The notification's serialized data. Identical to calling get_serialized_data.")
        .def("__repr__", [](const rs2::notification &n) {
            return n.get_description();
        });

    // not binding notifications_callback, templated

    py::class_<rs2::sensor, rs2::options> sensor(m, "sensor"); // No docstring in C++
    sensor.def("open", (void (rs2::sensor::*)(const rs2::stream_profile&) const) &rs2::sensor::open,
               "Open sensor for exclusive access, by commiting to a configuration", "profile"_a)
        .def("supports", (bool (rs2::sensor::*)(rs2_camera_info) const) &rs2::sensor::supports,
             "Check if specific camera info is supported.", "info")
        .def("supports", (bool (rs2::sensor::*)(rs2_option) const) &rs2::options::supports,
             "Check if specific camera info is supported.", "info")
        .def("get_info", &rs2::sensor::get_info, "Retrieve camera specific information, "
             "like versions of various internal components.", "info"_a)
        .def("set_notifications_callback", [](const rs2::sensor& self, std::function<void(rs2::notification)> callback) {
            self.set_notifications_callback(callback);
        }, "Register Notifications callback", "callback"_a)
        .def("open", (void (rs2::sensor::*)(const std::vector<rs2::stream_profile>&) const) &rs2::sensor::open,
             "Open sensor for exclusive access, by committing to a composite configuration, specifying one or "
             "more stream profiles.", "profiles"_a)
        .def("close", &rs2::sensor::close, "Close sensor for exclusive access.", py::call_guard<py::gil_scoped_release>())
        .def("start", [](const rs2::sensor& self, std::function<void(rs2::frame)> callback) {
            self.start(callback);
        }, "Start passing frames into user provided callback.", "callback"_a)
        .def("start", [](const rs2::sensor& self, rs2::syncer& syncer) {
            self.start(syncer);
        }, "Start passing frames into user provided syncer.", "syncer"_a)
        .def("start", [](const rs2::sensor& self, rs2::frame_queue& queue) {
            self.start(queue);
        }, "start passing frames into specified frame_queue", "queue"_a)
        .def("stop", &rs2::sensor::stop, "Stop streaming.", py::call_guard<py::gil_scoped_release>())
        .def("get_stream_profiles", &rs2::sensor::get_stream_profiles, "Retrieves the list of stream profiles supported by the sensor.")
        .def("get_active_streams", &rs2::sensor::get_active_streams, "Retrieves the list of stream profiles currently streaming on the sensor.")
        .def_property_readonly("profiles", &rs2::sensor::get_stream_profiles, "The list of stream profiles supported by the sensor. Identical to calling get_stream_profiles")
        .def("get_recommended_filters", &rs2::sensor::get_recommended_filters, "Return the recommended list of filters by the sensor.")
        .def(py::init<>())
        .def("__nonzero__", &rs2::sensor::operator bool) // No docstring in C++
        .def(BIND_DOWNCAST(sensor, roi_sensor))
        .def(BIND_DOWNCAST(sensor, depth_sensor))
        .def(BIND_DOWNCAST(sensor, color_sensor))
        .def(BIND_DOWNCAST(sensor, motion_sensor))
        .def(BIND_DOWNCAST(sensor, fisheye_sensor))
        .def(BIND_DOWNCAST(sensor, pose_sensor))
        .def(BIND_DOWNCAST(sensor, calibrated_sensor))
        .def(BIND_DOWNCAST(sensor, wheel_odometer));

    // rs2::sensor_from_frame [frame.def("get_sensor", ...)?
    // rs2::sensor==sensor?

    py::class_<rs2::roi_sensor, rs2::sensor> roi_sensor(m, "roi_sensor"); // No docstring in C++
    roi_sensor.def(py::init<rs2::sensor>(), "sensor"_a)
        .def("set_region_of_interest", &rs2::roi_sensor::set_region_of_interest, "roi"_a) // No docstring in C++
        .def("get_region_of_interest", &rs2::roi_sensor::get_region_of_interest) // No docstring in C++
        .def("__nonzero__", &rs2::roi_sensor::operator bool); // No docstring in C++

    py::class_<rs2::depth_sensor, rs2::sensor> depth_sensor(m, "depth_sensor"); // No docstring in C++
    depth_sensor.def(py::init<rs2::sensor>(), "sensor"_a)
        .def("get_depth_scale", &rs2::depth_sensor::get_depth_scale,
             "Retrieves mapping between the units of the depth image and meters.")
        .def("__nonzero__", &rs2::depth_sensor::operator bool); // No docstring in C++

    py::class_<rs2::color_sensor, rs2::sensor> color_sensor(m, "color_sensor"); // No docstring in C++
    color_sensor.def(py::init<rs2::sensor>(), "sensor"_a)
        .def("__nonzero__", &rs2::color_sensor::operator bool); // No docstring in C++

    py::class_<rs2::motion_sensor, rs2::sensor> motion_sensor(m, "motion_sensor"); // No docstring in C++
    motion_sensor.def(py::init<rs2::sensor>(), "sensor"_a)
        .def("__nonzero__", &rs2::motion_sensor::operator bool); // No docstring in C++

    py::class_<rs2::fisheye_sensor, rs2::sensor> fisheye_sensor(m, "fisheye_sensor"); // No docstring in C++
    fisheye_sensor.def(py::init<rs2::sensor>(), "sensor"_a)
        .def("__nonzero__", &rs2::fisheye_sensor::operator bool); // No docstring in C++

    py::class_<rs2::calibrated_sensor, rs2::sensor> cal_sensor( m, "calibrated_sensor" );
    cal_sensor.def( py::init<rs2::sensor>(), "sensor"_a )
        .def( "override_intrinsics", &rs2::calibrated_sensor::override_intrinsics, "intrinsics"_a )
        .def( "override_extrinsics", &rs2::calibrated_sensor::override_extrinsics, "extrinsics"_a )
        .def( "get_dsm_params", &rs2::calibrated_sensor::get_dsm_params )
        .def( "override_dsm_params", &rs2::calibrated_sensor::override_dsm_params, "dsm_params"_a )
        .def( "reset_calibration", &rs2::calibrated_sensor::reset_calibration )
        .def( "__nonzero__", &rs2::calibrated_sensor::operator bool );

    // rs2::depth_stereo_sensor
    py::class_<rs2::depth_stereo_sensor, rs2::depth_sensor> depth_stereo_sensor(m, "depth_stereo_sensor"); // No docstring in C++
    depth_stereo_sensor.def(py::init<rs2::sensor>())
        .def("get_stereo_baseline", &rs2::depth_stereo_sensor::get_stereo_baseline, "Retrieve the stereoscopic baseline value from the sensor.");

    py::class_<rs2::pose_sensor, rs2::sensor> pose_sensor(m, "pose_sensor"); // No docstring in C++
    pose_sensor.def(py::init<rs2::sensor>(), "sensor"_a)
        .def("import_localization_map", &rs2::pose_sensor::import_localization_map,
             "Load relocalization map onto device. Only one relocalization map can be imported at a time; "
             "any previously existing map will be overwritten.\n"
             "The imported map exists simultaneously with the map created during the most recent tracking "
             "session after start(),"
             "and they are merged after the imported map is relocalized.\n"
             "This operation must be done before start().", "lmap_buf"_a)
        .def("export_localization_map", &rs2::pose_sensor::export_localization_map,
             "Get relocalization map that is currently on device, created and updated during most "
             "recent tracking session.\n"
             "Can be called before or after stop().")
        .def("set_static_node", &rs2::pose_sensor::set_static_node,
             "Creates a named virtual landmark in the current map, known as static node.\n"
             "The static node's pose is provided relative to the origin of current coordinate system of device poses.\n"
             "This function fails if the current tracker confidence is below 3 (high confidence).",
             "guid"_a, "pos"_a, "orient"_a)
        .def("get_static_node", [](const rs2::pose_sensor& self, const std::string& guid) {
            rs2_vector pos;
            rs2_quaternion orient;
            bool res = self.get_static_node(guid, pos, orient);
            return std::make_tuple(res, pos, orient);
        }, "Gets the current pose of a static node that was created in the current map or in an imported map.\n"
           "Static nodes of imported maps are available after relocalizing the imported map.\n"
           "The static node's pose is returned relative to the current origin of coordinates of device poses.\n"
           "Thus, poses of static nodes of an imported map are consistent with current device poses after relocalization.\n"
           "This function fails if the current tracker confidence is below 3 (high confidence).",
           "guid"_a)
        .def("remove_static_node", &rs2::pose_sensor::remove_static_node,
             "Removes a named virtual landmark in the current map, known as static node.\n"
             "guid"_a)
        .def("__nonzero__", &rs2::pose_sensor::operator bool); // No docstring in C++

    py::class_<rs2::wheel_odometer, rs2::sensor> wheel_odometer(m, "wheel_odometer"); // No docstring in C++
    wheel_odometer.def(py::init<rs2::sensor>(), "sensor"_a)
        .def("load_wheel_odometery_config", &rs2::wheel_odometer::load_wheel_odometery_config,
             "Load Wheel odometer settings from host to device.", "odometry_config_buf"_a)
        .def("send_wheel_odometry", &rs2::wheel_odometer::send_wheel_odometry,
             "Send wheel odometry data for each individual sensor (wheel)",
             "wo_sensor_id"_a, "frame_num"_a, "translational_velocity"_a)
        .def("__nonzero__", &rs2::wheel_odometer::operator bool);
    /** end rs_sensor.hpp **/
}
<commit_msg>PR #7076 from Eran: fix GIL locks in calibrated_sensor APIs which can cause frame drops<commit_after>/* License: Apache 2.0. See LICENSE file in root directory.
Copyright(c) 2017 Intel Corporation. All Rights Reserved. */

#include "python.hpp"
#include "../include/librealsense2/hpp/rs_sensor.hpp"
#include "calibrated-sensor.h"

void init_sensor(py::module &m) {
    /** rs_sensor.hpp **/
    py::class_<rs2::notification> notification(m, "notification"); // No docstring in C++
    notification.def(py::init<>())
        .def("get_category", &rs2::notification::get_category,
             "Retrieve the notification's category.")
        .def_property_readonly("category", &rs2::notification::get_category,
             "The notification's category. Identical to calling get_category.")
        .def("get_description", &rs2::notification::get_description,
             "Retrieve the notification's description.")
        .def_property_readonly("description", &rs2::notification::get_description,
             "The notification's description. Identical to calling get_description.")
        .def("get_timestamp", &rs2::notification::get_timestamp,
             "Retrieve the notification's arrival timestamp.")
        .def_property_readonly("timestamp", &rs2::notification::get_timestamp,
             "The notification's arrival timestamp. Identical to calling get_timestamp.")
        .def("get_severity", &rs2::notification::get_severity,
             "Retrieve the notification's severity.")
        .def_property_readonly("severity", &rs2::notification::get_severity,
             "The notification's severity. Identical to calling get_severity.")
        .def("get_serialized_data", &rs2::notification::get_severity,
             "Retrieve the notification's serialized data.")
        .def_property_readonly("serialized_data", &rs2::notification::get_serialized_data,
             "The notification's serialized data. Identical to calling get_serialized_data.")
        .def("__repr__", [](const rs2::notification &n) {
            return n.get_description();
        });

    // not binding notifications_callback, templated

    py::class_<rs2::sensor, rs2::options> sensor(m, "sensor"); // No docstring in C++
    sensor.def("open", (void (rs2::sensor::*)(const rs2::stream_profile&) const) &rs2::sensor::open,
               "Open sensor for exclusive access, by commiting to a configuration", "profile"_a)
        .def("supports", (bool (rs2::sensor::*)(rs2_camera_info) const) &rs2::sensor::supports,
             "Check if specific camera info is supported.", "info")
        .def("supports", (bool (rs2::sensor::*)(rs2_option) const) &rs2::options::supports,
             "Check if specific camera info is supported.", "info")
        .def("get_info", &rs2::sensor::get_info, "Retrieve camera specific information, "
             "like versions of various internal components.", "info"_a)
        .def("set_notifications_callback", [](const rs2::sensor& self, std::function<void(rs2::notification)> callback) {
            self.set_notifications_callback(callback);
        }, "Register Notifications callback", "callback"_a)
        .def("open", (void (rs2::sensor::*)(const std::vector<rs2::stream_profile>&) const) &rs2::sensor::open,
             "Open sensor for exclusive access, by committing to a composite configuration, specifying one or "
             "more stream profiles.", "profiles"_a)
        .def("close", &rs2::sensor::close, "Close sensor for exclusive access.", py::call_guard<py::gil_scoped_release>())
        .def("start", [](const rs2::sensor& self, std::function<void(rs2::frame)> callback) {
            self.start(callback);
        }, "Start passing frames into user provided callback.", "callback"_a)
        .def("start", [](const rs2::sensor& self, rs2::syncer& syncer) {
            self.start(syncer);
        }, "Start passing frames into user provided syncer.", "syncer"_a)
        .def("start", [](const rs2::sensor& self, rs2::frame_queue& queue) {
            self.start(queue);
        }, "start passing frames into specified frame_queue", "queue"_a)
        .def("stop", &rs2::sensor::stop, "Stop streaming.", py::call_guard<py::gil_scoped_release>())
        .def("get_stream_profiles", &rs2::sensor::get_stream_profiles, "Retrieves the list of stream profiles supported by the sensor.")
        .def("get_active_streams", &rs2::sensor::get_active_streams, "Retrieves the list of stream profiles currently streaming on the sensor.")
        .def_property_readonly("profiles", &rs2::sensor::get_stream_profiles, "The list of stream profiles supported by the sensor. Identical to calling get_stream_profiles")
        .def("get_recommended_filters", &rs2::sensor::get_recommended_filters, "Return the recommended list of filters by the sensor.")
        .def(py::init<>())
        .def("__nonzero__", &rs2::sensor::operator bool) // No docstring in C++
        .def(BIND_DOWNCAST(sensor, roi_sensor))
        .def(BIND_DOWNCAST(sensor, depth_sensor))
        .def(BIND_DOWNCAST(sensor, color_sensor))
        .def(BIND_DOWNCAST(sensor, motion_sensor))
        .def(BIND_DOWNCAST(sensor, fisheye_sensor))
        .def(BIND_DOWNCAST(sensor, pose_sensor))
        .def(BIND_DOWNCAST(sensor, calibrated_sensor))
        .def(BIND_DOWNCAST(sensor, wheel_odometer));

    // rs2::sensor_from_frame [frame.def("get_sensor", ...)?
    // rs2::sensor==sensor?

    py::class_<rs2::roi_sensor, rs2::sensor> roi_sensor(m, "roi_sensor"); // No docstring in C++
    roi_sensor.def(py::init<rs2::sensor>(), "sensor"_a)
        .def("set_region_of_interest", &rs2::roi_sensor::set_region_of_interest, "roi"_a) // No docstring in C++
        .def("get_region_of_interest", &rs2::roi_sensor::get_region_of_interest) // No docstring in C++
        .def("__nonzero__", &rs2::roi_sensor::operator bool); // No docstring in C++

    py::class_<rs2::depth_sensor, rs2::sensor> depth_sensor(m, "depth_sensor"); // No docstring in C++
    depth_sensor.def(py::init<rs2::sensor>(), "sensor"_a)
        .def("get_depth_scale", &rs2::depth_sensor::get_depth_scale,
             "Retrieves mapping between the units of the depth image and meters.")
        .def("__nonzero__", &rs2::depth_sensor::operator bool); // No docstring in C++

    py::class_<rs2::color_sensor, rs2::sensor> color_sensor(m, "color_sensor"); // No docstring in C++
    color_sensor.def(py::init<rs2::sensor>(), "sensor"_a)
        .def("__nonzero__", &rs2::color_sensor::operator bool); // No docstring in C++

    py::class_<rs2::motion_sensor, rs2::sensor> motion_sensor(m, "motion_sensor"); // No docstring in C++
    motion_sensor.def(py::init<rs2::sensor>(), "sensor"_a)
        .def("__nonzero__", &rs2::motion_sensor::operator bool); // No docstring in C++

    py::class_<rs2::fisheye_sensor, rs2::sensor> fisheye_sensor(m, "fisheye_sensor"); // No docstring in C++
    fisheye_sensor.def(py::init<rs2::sensor>(), "sensor"_a)
        .def("__nonzero__", &rs2::fisheye_sensor::operator bool); // No docstring in C++

    py::class_<rs2::calibrated_sensor, rs2::sensor> cal_sensor( m, "calibrated_sensor" );
    cal_sensor.def( py::init<rs2::sensor>(), "sensor"_a )
        .def( "override_intrinsics",
              &rs2::calibrated_sensor::override_intrinsics,
              "intrinsics"_a,
              py::call_guard< py::gil_scoped_release >() )
        .def( "override_extrinsics",
              &rs2::calibrated_sensor::override_extrinsics,
              "extrinsics"_a,
              py::call_guard< py::gil_scoped_release >() )
        .def( "get_dsm_params",
              &rs2::calibrated_sensor::get_dsm_params,
              py::call_guard< py::gil_scoped_release >() )
        .def( "override_dsm_params",
              &rs2::calibrated_sensor::override_dsm_params,
              "dsm_params"_a,
              py::call_guard< py::gil_scoped_release >() )
        .def( "reset_calibration",
              &rs2::calibrated_sensor::reset_calibration,
              py::call_guard< py::gil_scoped_release >() )
        .def( "__nonzero__", &rs2::calibrated_sensor::operator bool );

    // rs2::depth_stereo_sensor
    py::class_<rs2::depth_stereo_sensor, rs2::depth_sensor> depth_stereo_sensor(m, "depth_stereo_sensor"); // No docstring in C++
    depth_stereo_sensor.def(py::init<rs2::sensor>())
        .def("get_stereo_baseline", &rs2::depth_stereo_sensor::get_stereo_baseline, "Retrieve the stereoscopic baseline value from the sensor.");

    py::class_<rs2::pose_sensor, rs2::sensor> pose_sensor(m, "pose_sensor"); // No docstring in C++
    pose_sensor.def(py::init<rs2::sensor>(), "sensor"_a)
        .def("import_localization_map", &rs2::pose_sensor::import_localization_map,
             "Load relocalization map onto device. Only one relocalization map can be imported at a time; "
             "any previously existing map will be overwritten.\n"
             "The imported map exists simultaneously with the map created during the most recent tracking "
             "session after start(),"
             "and they are merged after the imported map is relocalized.\n"
             "This operation must be done before start().", "lmap_buf"_a)
        .def("export_localization_map", &rs2::pose_sensor::export_localization_map,
             "Get relocalization map that is currently on device, created and updated during most "
             "recent tracking session.\n"
             "Can be called before or after stop().")
        .def("set_static_node", &rs2::pose_sensor::set_static_node,
             "Creates a named virtual landmark in the current map, known as static node.\n"
             "The static node's pose is provided relative to the origin of current coordinate system of device poses.\n"
             "This function fails if the current tracker confidence is below 3 (high confidence).",
             "guid"_a, "pos"_a, "orient"_a)
        .def("get_static_node", [](const rs2::pose_sensor& self, const std::string& guid) {
            rs2_vector pos;
            rs2_quaternion orient;
            bool res = self.get_static_node(guid, pos, orient);
            return std::make_tuple(res, pos, orient);
        }, "Gets the current pose of a static node that was created in the current map or in an imported map.\n"
           "Static nodes of imported maps are available after relocalizing the imported map.\n"
           "The static node's pose is returned relative to the current origin of coordinates of device poses.\n"
           "Thus, poses of static nodes of an imported map are consistent with current device poses after relocalization.\n"
           "This function fails if the current tracker confidence is below 3 (high confidence).",
           "guid"_a)
        .def("remove_static_node", &rs2::pose_sensor::remove_static_node,
             "Removes a named virtual landmark in the current map, known as static node.\n"
             "guid"_a)
        .def("__nonzero__", &rs2::pose_sensor::operator bool); // No docstring in C++

    py::class_<rs2::wheel_odometer, rs2::sensor> wheel_odometer(m, "wheel_odometer"); // No docstring in C++
    wheel_odometer.def(py::init<rs2::sensor>(), "sensor"_a)
        .def("load_wheel_odometery_config", &rs2::wheel_odometer::load_wheel_odometery_config,
             "Load Wheel odometer settings from host to device.", "odometry_config_buf"_a)
        .def("send_wheel_odometry", &rs2::wheel_odometer::send_wheel_odometry,
             "Send wheel odometry data for each individual sensor (wheel)",
             "wo_sensor_id"_a, "frame_num"_a, "translational_velocity"_a)
        .def("__nonzero__", &rs2::wheel_odometer::operator bool);
    /** end rs_sensor.hpp **/
}
<|endoftext|>